【问题标题】:Run a for loop with two or more variables without using nested loops在不使用嵌套循环的情况下运行具有两个或更多变量的 for 循环
【发布时间】:2018-09-09 19:38:19
【问题描述】:

我想运行一个包含多个同时运行且不嵌套的变量的 for 循环。

我的代码如下

for (i, j in c(1,2,3), c("a","b","c")){
print(i)
print(j)
}

我想打印出来

1
a
2
b
3
c

我该怎么做?

【问题讨论】:

    标签: r for-loop


    【解决方案1】:

    我们可以循环遍历向量的序列

    for(i in seq_along(x1)) {
            print(x1[i])
            print(y1[i])
      }
    

    类似于在python中使用range循环的选项

    x = [1, 2, 3]
    y = ['a', 'b', 'c']
    for i in range(len(x)):
        print(x[i])
        print(y[i])
    

    数据

    x1 <- 1:3
    y1 <- letters[1:3]
    

    【讨论】:

    • 谢谢!我喜欢它如何扩展到更多变量,例如 for(i in seq_along(x1)) {print(x1[i]);打印(y1[i]); print(z1) } x1
    【解决方案2】:

    试试mapply:

     mapply(function(x, y) {print(x); print(y)}, x = 1:3, y = letters[1:3])
    

    Map 也做了类似的事情。

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多