这是一个基于Pokémon Stats 数据的完全可重现的示例。我不只是将输入文件写入list(),而是使用assign() 在全局环境中模拟一组数据帧。
download.file("https://raw.githubusercontent.com/lgreski/pokemonData/master/pokemonData.zip",
"pokemonData.zip",
method="curl",mode="wb")
unzip("pokemonData.zip")
thePokemonFiles <- list.files("./pokemonData",
full.names=TRUE)
filenames <- substr(list.files("./pokemonData",full.names = FALSE),1,5)
results <- lapply(1:length(thePokemonFiles),function(x) {
# read data and assign to a name in global environment
data <- read.csv(thePokemonFiles[x],stringsAsFactor = FALSE)
assign(filenames[x],data,globalenv())
return(TRUE)
})
此时我们在全局环境中有 7 个数据框,分别命名为 gen01 到 gen07。
接下来,我们生成所需的排序顺序作为向量。我们将使用它以及来自filenames 向量的名称来获取数据并以所需的数据帧排序顺序构建输出列表。
desiredSortOrder <- c(1,3,5,7,2,4,6)
sortedDataFrames <- lapply(desiredSortOrder,function(x){
get(filenames[x])
})
# verify generation numbers by printing first row of each data frame
lapply(sortedDataFrames,function(x){
x[1,c(1,2,12)]
})
由于每个数据帧中的Generation 列与其关联的文件名匹配,我们可以通过打印每个数据帧的第一行来验证排序顺序。
>lapply(sortedDataFrames,function(x){
+ x[1,c(1,2,12)]
+ })
[[1]]
Number Name Generation
1 1 Bulbasaur 1
[[2]]
Number Name Generation
1 252 Treecko 3
[[3]]
Number Name Generation
1 494 Victini 5
[[4]]
Number Name Generation
1 722 Rowlet 7
[[5]]
Number Name Generation
1 152 Chikorita 2
[[6]]
Number Name Generation
1 387 Turtwig 4
[[7]]
Number Name Generation
1 650 Chespin 6
>