Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

for loop - foreach with list in R

I am trying to access numbers from list/vector, in general when I call normally not getting issue. But when I use it with foreach or for loop getting NULL as a result Ex1:

aa<- c(7, 4, 10)
bb <- list(90,87,45)

aa[1] will result 7, bb[1] result 90 this is pretty straight forward

But when I try with for or foreach loop:


for(i in aa) aa[i]
or
for(i in aa) {bb[i]}

not getting any result 

ex2:

foreach(i = aa) %dopar% {aa[i]}
foreach(i = aa) %dopar% bb[i]

getting result as Null

Could some one please help and correct above code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not getting any result because for loop does not return anything. You can access the variables in for loop which can be demonstrated with a print statement.

for(i in seq_along(aa)) print(aa[i])

#[1] 7
#[1] 4
#[1] 10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...