简体   繁体   English

嵌套循环遍历R中的不同列表

[英]Nested loop through the different lists in R

I have the 5 lists of length 10, d1,...,d5 . 我有5个长度为10, d1,...,d5
for example the d1 is : 例如d1是:

> d1
[[1]]
 [1] -0.4470862 -7.2330362  2.0060165 -1.8135874 -6.3239906 -9.2819973 -4.5281328 -0.4646620 -3.6033140 -8.4078084

[[2]]
 [1]  0.8860549 -5.5916677  4.3382399 -5.6031842 -7.1132885  1.8388706  5.3161508 12.9872906 10.9063864 -2.7285185

[[3]]
 [1]  1.7715003 -5.3555033  6.7489209  8.6213950 -2.1861336  8.8199678  6.3897033 -8.7263417  0.4513869  3.7055572

[[4]]
 [1]  -6.4443679  -7.8786053   1.2553411  -9.4590218  -3.3743598 -14.6997473 -11.4365114  -0.3903306  -0.6343901   0.1218937

[[5]]
 [1]  -7.1302642  11.2561616   7.9592310  -0.9878423   0.2744908   2.2974143  -2.5867071  -9.6975011 -10.9544252   5.3961757

[[6]]
 [1] -12.4285771   1.9922676  -2.6495977   2.3891633  -4.0980340 -15.3845265  -4.8952363  -3.0497065  -0.6652166  -0.7398617

[[7]]
 [1]  -1.4175504 -11.3625955  -6.2915938  -7.5563334   0.7397468  -7.4810663  -1.2341943  -5.1838253   2.4293057   2.1604598

[[8]]
 [1]  -8.9740261  -3.8747773  -8.4827669  -2.6074740 -16.5657409  -0.6334476 -10.2824297 -13.6752398  -1.8896523   5.5975585

[[9]]
 [1]  -2.7644181  -4.4193104  -3.0591752 -11.0800374  -0.2166242   7.6568081  10.2937062   0.8078439  -5.6475922   0.1152055

[[10]]
 [1]  -4.2258527  -3.7496935  -7.4994027   2.4172585  -0.9224533   3.7842335  -5.0711585 -10.5714328  -1.4858401  -1.3034318

I want to compare the elements of these list with some constants, c1,...,c5 and assign the result to another list. 我想将这些列表的元素与一些常量c1,...,c5 ,并将结果分配给另一个列表。
This is the code: 这是代码:

result<-list()
for(i in 1:10){for (j in 1:10)
  if (d1[[i]][j]>=c1 | d2[[i]][j]>=c2| d3[[i]][j]>=c3 | d4[[i]][j]>=c4| d5[[i]][j]>=c5) 
  { result[[i]][j]==TRUE}}

But I receive this result: 但是我收到以下结果:

> result
list()

Please help me to modify the code. 请帮我修改代码。

You are not assigning anything with { result[[i]][j]==TRUE}} . 您没有使用{ result[[i]][j]==TRUE}}分配任何内容。 Don't you need { result[[i]][j]=TRUE}} or { result[[i]][j] <- TRUE}} ? 您是否不需要{ result[[i]][j]=TRUE}}{ result[[i]][j] <- TRUE}}

UPDATE: perhaps the first time your conditions hold is when i = 3 and j = 5 for example. 更新:也许您的条件第一次成立是例如当i = 3和j = 5时。 An empty list does not contain anything yet, so it cannot assign something at the 3rd nested list and its 5th element. 空列表尚不包含任何内容,因此它无法在第3个嵌套列表及其第5个元素上分配内容。 You could create the "target" list before and fill it with NAs, like this, and run your for loop afterwards: 您可以像这样在之前创建“目标”列表并用NA填充它,然后再运行for循环:

result <- list(rep(NA,10),rep(NA,10),rep(NA,10),rep(NA,10),rep(NA,10),rep(NA,10),rep(NA,10),rep(NA,10),rep(NA,10),rep(NA,10))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM