如何在rbind.fill中使用paste函数的输出?

时间:2013-10-06 15:06:06

标签: r rbind

我有一个数据框列表,我正在尝试rbind.fill,因为它们没有相同数量的列。数据帧的名称为x1,x2,... x10。

我的代码:

x.list<-list(c(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10))
library(plyr)
rbind.fill(x.list) 

此代码有效,但我试图避免使用paste0编写所有数据帧,即

x.list1<-as.list(paste0(x,1:10))

x.list1将x1,x2,...解释为字符而不是数据帧:

    str(x.list1)
List of 10
 $ : chr "x1"
 $ : chr "x2"
 $ : chr "x3"
 $ : chr "x4"
 $ : chr "x5"
 $ : chr "x6"
 $ : chr "x7"
 $ : chr "x8"
 $ : chr "x9"
 $ : chr "x10"

所以,我不能使用rbind.fill,因为它需要数据帧列表。我已按照建议here

尝试使用mget
rbind.fill(mget(x.list1))

但是,我收到了错误,

Error in mget(x.list1) : argument "envir" is missing, with no default

设置环境(如前面问题的答案评论中所述)也无济于事:

rbind.fill(mget(x.list1,envir = .GlobalEnv))
Error in mget(x.list1, envir = .GlobalEnv) : invalid first argument

有任何解决此问题的建议吗?

以下是示例数据帧x1,x2和x3:

x1<-structure(list(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3, 
24.4, 22.8, 19.2), cyl = c(6, 6, 4, 6, 8, 6, 8, 4, 4, 6), disp = c(160, 
160, 108, 258, 360, 225, 360, 146.7, 140.8, 167.6), hp = c(110, 
110, 93, 110, 175, 105, 245, 62, 95, 123)), .Names = c("mpg", 
"cyl", "disp", "hp"), row.names = c("Mazda RX4", "Mazda RX4 Wag", 
"Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Valiant", 
"Duster 360", "Merc 240D", "Merc 230", "Merc 280"), class = "data.frame")

x2<-structure(list(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3, 
24.4, 22.8, 19.2), cyl = c(6, 6, 4, 6, 8, 6, 8, 4, 4, 6), disp = c(160, 
160, 108, 258, 360, 225, 360, 146.7, 140.8, 167.6), hp = c(110, 
110, 93, 110, 175, 105, 245, 62, 95, 123), drat = c(3.9, 3.9, 
3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.92), wt = c(2.62, 
2.875, 2.32, 3.215, 3.44, 3.46, 3.57, 3.19, 3.15, 3.44)), .Names = c("mpg", 
"cyl", "disp", "hp", "drat", "wt"), row.names = c("Mazda RX4", 
"Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", 
"Valiant", "Duster 360", "Merc 240D", "Merc 230", "Merc 280"), class = "data.frame")

x3<-structure(list(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3, 
24.4, 22.8, 19.2, 17.8), cyl = c(6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 
6), disp = c(160, 160, 108, 258, 360, 225, 360, 146.7, 140.8, 
167.6, 167.6)), .Names = c("mpg", "cyl", "disp"), row.names = c("Mazda RX4", 
"Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", 
"Valiant", "Duster 360", "Merc 240D", "Merc 230", "Merc 280", 
"Merc 280C"), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

lapply与匿名函数和get一起使用。

# use: 
lapply(paste0("x", 1:10), function(x) get(x))

# instead of: 
as.list(paste0(x,1:10))