如何迭代 R 中的列表列表?
How to iterate over a list of lists in R?
我是 R
的新手,无法在 R
中找到以下 Python
代码的计数器代码。
请帮助
list1 = [10, 20] # or a tuple
list2 = [30, 40] # or a tuple
mylist = [list1, list2] # can be tuple of tuples also
for _list in mylist:
a = _list[0]
b = _list[1]
# usage of a and b
我编写了以下 R 脚本:
list1 <- list(10, 20)
list2 <- list(30, 40)
mylist <- list(list1, list2)
for( j in 1:length(mylist))
{
print(j)
list1=mylist[[j]]
print(list1)
# Works perfect till here
# Error in below lines
a=list1[[0]]
b=list1[[1]]
# usage of a and b
}
在 R
中,索引从 1 而不是 0 开始 - Python
和 R
之间的区别。因此,如果我们将其更改为 1
和 2
,它就会起作用。此外,1:length
可能会替换为错误较少的 seq_along
for( j in seq_along(mylist)){
print(j)
list1 = mylist[[j]]
print(list1)
a=list1[[1]]
b=list1[[2]]
# usage of a and b
}
[1] 1
[[1]]
[1] 10
[[2]]
[1] 20
[1] 2
[[1]]
[1] 30
[[2]]
[1] 40
注意:list1
、a
、b
是在循环中创建的对象,并且会在每次迭代中更新。最后的结果还不清楚
您的 python
代码的翻译可能如下所示
> for (lst in mylist) {
+ a <- lst[[1]]
+ b <- lst[[2]]
+ print(c(a, b))
+ }
[1] 10 20
[1] 30 40
我是 R
的新手,无法在 R
中找到以下 Python
代码的计数器代码。
请帮助
list1 = [10, 20] # or a tuple
list2 = [30, 40] # or a tuple
mylist = [list1, list2] # can be tuple of tuples also
for _list in mylist:
a = _list[0]
b = _list[1]
# usage of a and b
我编写了以下 R 脚本:
list1 <- list(10, 20)
list2 <- list(30, 40)
mylist <- list(list1, list2)
for( j in 1:length(mylist))
{
print(j)
list1=mylist[[j]]
print(list1)
# Works perfect till here
# Error in below lines
a=list1[[0]]
b=list1[[1]]
# usage of a and b
}
在 R
中,索引从 1 而不是 0 开始 - Python
和 R
之间的区别。因此,如果我们将其更改为 1
和 2
,它就会起作用。此外,1:length
可能会替换为错误较少的 seq_along
for( j in seq_along(mylist)){
print(j)
list1 = mylist[[j]]
print(list1)
a=list1[[1]]
b=list1[[2]]
# usage of a and b
}
[1] 1
[[1]]
[1] 10
[[2]]
[1] 20
[1] 2
[[1]]
[1] 30
[[2]]
[1] 40
注意:list1
、a
、b
是在循环中创建的对象,并且会在每次迭代中更新。最后的结果还不清楚
您的 python
代码的翻译可能如下所示
> for (lst in mylist) {
+ a <- lst[[1]]
+ b <- lst[[2]]
+ print(c(a, b))
+ }
[1] 10 20
[1] 30 40