[英]R: How to replace list of names by list of dataframes?
I want to convert a list of dataframes's names to a list of dataframes. 我想将数据框名称列表转换为数据框列表。
Example: 例:
datalist <- list("mtcars","swiss","iris")
Then I want to do something like 然后我想做些类似的事情
for(i in 1:length(datalist)) {
datalist[[i]] <- parse(datalist[[i]])
}
So when I run datalist[[i]]
I see the same as this 因此,当我运行
datalist[[i]]
我看到的与此相同
> mtcars
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
and not 并不是
> datalist[[i]]
"mtcars"
mget
is the appropriate function. mget
是适当的功能。 It works on a character vector of object names and returns a list of objects. 它对对象名称的字符向量起作用,并返回对象列表。 I use
unlist
to convert your list to a character vector: 我使用
unlist
将您的列表转换为字符向量:
mget(unlist(datalist))
Note that this will not work on the built-in data frames in your example unless (a) you set the inherits
option to TRUE
like this: mget(unlist(datalist), inherits = TRUE)
, or (b) they have already been loaded into the global environment (eg, using data()
). 请注意,这在您的示例中的内置数据帧上将不起作用,除非(a)将此
inherits
选项设置为TRUE
: mget(unlist(datalist), inherits = TRUE)
或(b)它们已经被加载到全局环境中(例如,使用data()
)。
One advantage of mget
compared to other answers proposed here is that the resulting list is created with the names of the objects as the names of the list. 与此处提出的其他答案相比,
mget
一个优点是,使用对象名称作为列表名称来创建结果列表。
Consider using get
: 考虑使用
get
:
datalist <- list("mtcars","swiss","iris")
dfList <- lapply(datalist, get)
for(i in 1:length(dfList)) {
print(head(dfList[[i]]))
}
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
# Fertility Agriculture Examination Education Catholic Infant.Mortality
# Courtelary 80.2 17.0 15 12 9.96 22.2
# Delemont 83.1 45.1 6 9 84.84 22.2
# Franches-Mnt 92.5 39.7 5 5 93.40 20.2
# Moutier 85.8 36.5 12 7 33.77 20.3
# Neuveville 76.9 43.5 17 15 5.16 20.6
# Porrentruy 76.1 35.3 9 7 90.57 26.6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
Instead of 代替
parse(datalist[[i]])
use: 采用:
eval(parse(text = datalist[[i]]))
You need to evaluate the output of parse. 您需要评估解析的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.