Вопрос

I have a list of dataframe which I am trying to rbind.fill as they don't have the same number of columns. The dataframes are names as x1,x2,...x10.

My code :

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

This code works, but I am trying to avoid writing all dataframe by using paste0, i.e.

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

x.list1 interprets x1, x2,... as characters rather than as dataframe:

    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"

So, I can't use rbind.fill since it expects list of dataframes. I have tried using mget as suggested here

rbind.fill(mget(x.list1))

But, I got the error,

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

Setting the environment (as mentioned in the comment of answer to earlier question) doesn't help either:

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

Any suggestion to fix this issue?

Here is the sample dataframes x1,x2,and 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")
Это было полезно?

Решение

use lapply with an anonymous function and with get.

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

# instead of: 
as.list(paste0(x,1:10))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top