【问题标题】:for loops in r are giving me a headacher 中的 for 循环让我头疼
【发布时间】: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 &lt;- 1:4 而不是a &lt;- list(1:4),您的代码就可以工作了。当向量可以使用时不要使用列表。

标签: r loops for-loop


【解决方案1】:

您应该将数据存储在长度为 4 的列表中,现在您将数据存储为长度为 1 的列表。

a <- as.list(1:4)
for (i in a) {
  print(i)
  print("should be between the numbers")
}

#[1] 1
#[1] "should be between the numbers"
#[1] 2
#[1] "should be between the numbers"
#[1] 3
#[1] "should be between the numbers"
#[1] 4
#[1] "should be between the numbers"

您仍然可以使用a &lt;- list(1:4),但在这种情况下,您必须将循环更改为:

for (i in a[[1]]) {
  print(i)
  print("should be between the numbers")
}

【讨论】:

    【解决方案2】:

    您可以修改代码如下。

    a<-(1:4)
    for (i in a){
      print(i)
      print("should be between the numbers")
    }
    
    #[1] 1
    #[1] "should be between the numbers"
    #[1] 2
    #[1] "should be between the numbers"
    #[1] 3
    #[1] "should be between the numbers"
    #[1] 4
    #[1] "should be between the numbers"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      相关资源
      最近更新 更多