绑定两个具有不同列名和行名的数据框

Binding two data frames with different names of columns and rows

R 位用户, 我有两个不同的数据框。我想在每个州的最后一个州名称之后插入 (e.t., rbind) 第二个数据框 (df_2)。这是两个数据框的假例子:

states = rep(c("AL", "NE", "AR", "MO", "WA"),times = c(10, 10, 10, 10, 10))
schools = randomNames::randomNames(50) ## 5 first last names separated by a space
Gender = rep(c("male", "female"),times = c(18,32))
type = rep(c("private", "public"),times = c(20,30))
item1 = rnorm(50, mean=25, sd=5)
item2 = rnorm(50, mean=30, sd=5)
item3 = rnorm(50, mean=15, sd=5)
df_1 = data.frame(states, schools, Gender, type, item1, item2, item3)

FirstQuestionOptions = c("Yes", "No")
SeconsQuestionOptions = c("one", "two")
ThirdQuestionOptions = c(88, 90)
df_2 = data.frame(FirstQuestionOptions, SeconsQuestionOptions, ThirdQuestionOptions)


df_3 should be the combination of df_1 and df_2. 

然后,想要使用以下内容将每个状态数据导出到单独的 excel 文件中:

list_data <- split(df_3, df_3$states)
Map(openxlsx::write.xlsx, list_data, paste0(names(list_data), '.xlsx'))

提前致谢。

为此我是:

  1. 遍历数据集中每个唯一的州名称
  2. 每次新建一个工作簿
  3. 正在将工作表添加到该州名称的工作簿
  4. 过滤 df_1 仅关注感兴趣的状态数据
  5. 正在将州的数据添加到工作表
  6. 然后给每个写 df_2 -- 我只是随意选择了 J 列(即第 10 列),但是你可以在任何你想写的地方写。

您还可以使用 openxlsx 中的样式命令指定列是否应具有特定宽度。

library(openxlsx)
library(tidyverse) #probably don't need this whole library but I usually just have this loaded
for(i in unique(states)){

    wb<- createWorkbook()
addWorksheet(wb, sheetName = i)
df_i = df_1 %>% 
    filter(states == i)
writeData(wb, sheet = i, x = df_i, startCol = 5)
writeData(wb, sheet = i, df_2, startCol = 1)
saveWorkbook(wb, paste0('YOURPATHWAY',i,".xlsx"), overwrite = TRUE)

}