在R中,如何同时循环多个变量?

huangapple go评论73阅读模式
英文:

In R, how can loop multiple variable at the same?

问题

我想知道如何在R中同时循环多个变量。

例如,

a = c(1, 2, 3)
b = c(4, 5, 6)

然后使用for循环,下面的代码不起作用。

for (i, j in a, b) {
    print(i)
    print(j)
}

在Python中,

for i, j in zip(a, b):
    print(i)
    print(j)

是可能的。我该如何在R中实现这个功能?

英文:

I am wondering of how can I loop the multiple variables at the same time in R.

For example,

a = c(1, 2, 3)
b = c(4, 5, 6)

And then for loop, the below code didnt work.

for (i, j in a, b) {
    print(i)
    print(j)
}

In Python,

for i,j in zip(a,b):
  print(i)
  print(j)

it is possible. How can I do this in R?

答案1

得分: 2

以下是翻译好的部分:

这是R中无法实现的,在这种情况下,最好的解决方案是迭代一个数组的长度,并打印每个数组中的位置的值:

a = c(1, 2, 3)
b = c(4, 5, 6)
for(i in 1:length(a))
{
  print(a[i])
  print(b[i])
}
英文:

It's not possible using R, in this case the best solution is to iterate over the length of one array and print the value in the position of each array:

a = c(1, 2, 3)
b = c(4, 5, 6)
for(i in 1:length(a))
{
  print(a[i])
  print(b[i])
}

答案2

得分: 0

In R,这甚至更简单:

mapply(function(x,y) print(x,y), a, b)

英文:

In R, it's even simpler:

mapply(function(x,y) print(x,y), a, b)

答案3

得分: 0

如果您想打印所有9种可能的组合,您需要使用嵌套的for循环

a = c(1, 2, 3)
b = c(4, 5, 6)
for(i in 1:length(a))
{
  for(j in 1:length(b))
  {
    print(a[i])
    print(b[j])
  }
}
英文:

If you want to print all 9 possible combinations, you need to use a nested for loop

a = c(1, 2, 3)
b = c(4, 5, 6)
for(i in 1:length(a))
{
  for(j in 1:length(b))
  {
    print(a[i])
    print(b[j])
  }
}

答案4

得分: 0

我们可以使用 seq_along

for(i in seq_along(a)) {
   print(a[i])
   print(b[i])
  }
英文:

We can use seq_along

for(i in seq_along(a)) {
   print(a[i])
   print(b[i])
  }

huangapple
  • 本文由 发表于 2020年1月6日 22:11:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定