首页 > 解决方案 > 将列表中每个数据帧的特定列重命名为循环的一部分

问题描述

基本上,我想在重命名第二列后创建多个数据框并将它们附加到一个列表(全部在一个循环中)。下面是示例代码。

问题是 - 我想将每个数据框的第二列重命名为循环变量,但还无法管理。

### create a blank list
temp_list<-vector("list",)

### create a vector with values to use in the loop

temp_years<-c("2010","2011")

### loop to generate the dataframes with name i
##add to the list above, then rename column 2
### of each dataframe to the loop variable (i). 

for (i in temp_years){
  temp_df<-data.frame(coltest11=runif(4),coltest12=runif(4))
  temp_list[[i]]<-temp_df
  names(temp_list[[i]][2])<-i
}

在列标题方面所需的输出:

$`2010`
  coltest11    **2010**
1 0.4781636 0.28835747
2 0.1413173 0.84415993
3 0.6564438 0.01405185
4 0.3046113 0.83951115

$`2011`
  coltest11    **2011**
1 0.8050338 0.2284567
2 0.3049061 0.8308597
3 0.2920562 0.8118845
4 0.3452323 0.9222456

标签: r

解决方案


你可以试试这个:

### create a blank list
temp_list<-list()

### create a vector with values to use in the loop

temp_years<-c("2010","2011")

#Loop

for (i in temp_years){
  temp_df<-data.frame(coltest11=runif(4),coltest12=runif(4))
  temp_list[[i]]<-temp_df
  names(temp_list[[i]])[2]<-i
}

输出:

$`2010`
  coltest11      2010
1 0.1481673 0.5234788
2 0.4055919 0.5426163
3 0.2353523 0.5847577
4 0.5258541 0.6792990

$`2011`
  coltest11      2011
1 0.4292431 0.7717647
2 0.2160180 0.4033482
3 0.8142830 0.6944202
4 0.5900886 0.4449840

推荐阅读