Friday, 15 May 2015

for loop in r not working -



for loop in r not working -

this question has reply here:

why r objects not print in function or “for” loop? 3 answers

we have vector of vectors

s = c(c(7,6,8,5,9),c(3,2,4),c(6,5,7))

why output right values console

mean(s[1]) mean(s[2]) mean(s[3])

while next yields nothing?

for (i in 1:3) { mean(s[i]) }

by using c, concatenating 3 vectors single vector. so, mean of s[1] or s[2] or s[3] mean of single element instead of vector. i.e.

s = c(c(7,6,8,5,9),c(3,2,4),c(6,5,7)) s[1] #[1] 7 s[2] #[1] 6 s[3] #[1] 8

but, if assume have list of vectors

s <- list(c(7,6,8,5,9),c(3,2,4),c(6,5,7))

you can mean of list elements using sapply

sapply(s, mean) #[1] 7 3 6

based on for loop code, if utilize [ instead of [[ list

for(i in 1:3){ print(mean(s[i]))} #[1] na #[1] na #[1] na #warning messages: #1: in mean.default(s[i]) : #argument not numeric or logical: returning na for(i in 1:3){ print(mean(s[[i]]))} #[1] 7 #[1] 3 #[1] 6

for storing output, can create new object out

out <- vector('numeric', length(s)) for(i in 1:3) out[i] <- mean(s[[i]]) out #[1] 7 3 6

r loops for-loop

No comments:

Post a Comment