我已经通过for循环创建了15个单独的数据框,每个数据框代表每个调查项目的得分,这些得分包括15个不同的比例/主题区域。根据我的主题区域的原始顺序,它们被命名为df1到df15,但是我想根据不同的排序顺序将它们放在一个列表中。我有一个单独的数据框,称为topic.area,列出了15个主题区域中的每个区域,它们的原始顺序,并按新的排序顺序排列:
主题区域...原始顺序...排序顺序领导........ 3..3 ....... 1订婚..... 1 ............... 2创新......... 2 ................ 3等等...
我本质上想执行以下操作,但是代码对我不起作用。我对R非常陌生,因此感谢所有不太高级的解决方案,因此我了解它们背后的逻辑。
myList<- list()
for(m in 1:15) {
myList[[m]]<- paste("df", topic.area$orig.order[m], sep = "")
}
我认为问题是您不能在分配命令中使用粘贴功能,但我不知道要解决此问题。
获取列表中的所有数据框。如前所述,orig.order
已经对此进行了排序。
list_df <- mget(paste0('df', 1:15))
您可以直接通过sort.order
来安排它们:
sorted_list_df <- list_df[topic.area$sort.order]
这里是一个基于口袋妖怪统计数据的完全可复制的示例。
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)
})
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)]
})
...和结果:
>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
>