使用循环,rbind和数据框名称列表命名数据框的困难

时间:2018-12-31 21:14:45

标签: r loops

我是新的R程序员。我正在尝试使用rbind组合临时数据帧。我需要每组组合数据集的名称来自循环迭代通过的数据帧列表。

我可以使临时文件正确组合,但是如果我使用遍历名称列表的数据框名称,则无法使用。我搜寻了又搜寻了,也叫程序员朋友,无济于事。谢谢!!

#initialize empty data frames
sheet1 <- data.frame(County = character(), Winner = character())
sheet2 <- data.frame(County = character(), Winner = character())
sheet3 <- data.frame(County = character(), Winner = character())
sheet4 <- data.frame(County = character(), Winner = character())

#put empty data frames into a list
sheet_dfs <- c(sheet1, sheet2, sheet3, sheet4)

#pull information from different Excel sheets for each iteration (not shown here)
#and write to element of list of dataframes 
for (i in 1:3) {
  temp1 <- data.frame(c("Cobb","Clayton","Fulton"), c("Kemp","Abrams","Smith"))
  colnames(temp1) <- c("County","Winner")
  temp2 <- data.frame(c("Henry","Polk","Gwinnett"), c("Fuller","Parker","Newsome"))
  colnames(temp2) <- c("County","Winner")
  sheet_dfs[[i]] <- rbind(temp1,temp2)}

sheet1 #expecting a data frame with names, what am I doing wrong?
sheet2 #expecting a data frame with names, what am I doing wrong?
sheet3 #expecting a data frame with names, what am I doing wrong?

test <- rbind(temp1,temp2)
test #this is exactly the output I need for my dataframes sheet1,sheet2,sheet3. 
returns:
County  Winner
1     Cobb    Kemp
2  Clayton  Abrams
3   Fulton   Smith
4    Henry  Fuller
5     Polk  Parker
6 Gwinnett Newsome

1 个答案:

答案 0 :(得分:2)

首先,您需要创建一个适当的命名列表。您的初始列表分配只是通过c创建一个向量。此外,您需要通过[[或名称正确访问列表元素。请参见下面的代码修改。

# set up named list programmatically
sheet_names = paste0("sheet", 1:4)
sheet_dfs = setNames(vector(length = length(sheet_names), mode = "list"), sheet_names)
# you can also create a named list as follows, which is, however, less programmatically
# sheet_dfs = list("sheet1" = sheet1, "sheet2" = sheet2, ...)

# your temp assignments...
#pull information from different Excel sheets for each iteration (not shown here)
#and write to element of list of dataframes 
for (i in 1:3) {
  temp1 <- data.frame(County = c("Cobb","Clayton","Fulton"), Winner = c("Kemp","Abrams","Smith"))
  temp2 <- data.frame(County = c("Henry","Polk","Gwinnett"), Winner = c("Fuller","Parker","Newsome"))
  sheet_dfs[[i]] <- rbind(temp1,temp2)
}

# access the list via name or index
sheet_dfs[[1]]
sheet_dfs["sheet1"]