r - 将列表中每个数据帧的特定列重命名为循环的一部分
问题描述
基本上,我想在重命名第二列后创建多个数据框并将它们附加到一个列表(全部在一个循环中)。下面是示例代码。
问题是 - 我想将每个数据框的第二列重命名为循环变量,但还无法管理。
### 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
解决方案
你可以试试这个:
### 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
推荐阅读
- matplotlib - sns.clustermap 记号丢失
- python - 将包含数组的文件的行转换为字典列表
- python - 将 Pandas DataFrame 的“numpy”操作转换为 PySpark DataFrame 的等效操作
- java - kafka 和 kafka-clients 有什么区别?
- c - printf %f 地址错误
- javascript - 打字稿是否允许接口和字符串联合类型?
- json - 为什么我不能在 Flatlist 中显示我的项目?
- java - 我无法在 Vaadin 组件中调用 JpaReposistory api
- java - 在 lambda 表达式中分配局部变量
- python - 这个片段是如何工作的?“pk=request.POST['选择']”