【发布时间】:2021-02-03 03:47:07
【问题描述】:
a<-list(1:4)
for (i in a){
print(i)
print("should be between the numbers")
}
output:
[1] 1 2 3 4
[1] "should be between the numbers"
expected output:
[1] 1
[1] "should be between the numbers"
[2] 2
[2] "should be between the numbers"
[3] 3
[3] "should be between the numbers"
[4] 4
[4] "should be between the numbers"
为什么会发生这种情况?如何获得看起来更接近预期输出的输出?
我希望能够做类似的事情:
list_of_data_frame_names<-list("bob","jill","jack")
list_of_data_frames<-list(bob,jill,jack)
a<-list(1:4)
for (i in a){
q<-list_of_dataframes[[i]] %>% names() %>% length()
b<-list(2:q)
for (j in b){
names(list_of_data[[i]])[j] <- paste(names(list_of_data[i]))[j], list_of_data_frame_names[i], sep="_")
}
我正在处理多个数据集,这些数据集涵盖相同的数据但具有不同的列名称(例如费用、费用和 Total_Expenses),所以我想知道哪一列来自哪个数据集但不想这样做全部手工。请注意,内部循环的工作原理我已经对其进行了测试,如果需要,我可以为每个数据集手动运行它,但这会使将来添加的数据集更加困难,并且对同一个循环进行 8 次硬编码并不是好的编码实践。
【问题讨论】:
-
问题是
list。使用a <- 1:4而不是a <- list(1:4),您的代码就可以工作了。当向量可以使用时不要使用列表。