Grace
Grace

Reputation: 173

How to apply each of a series variables to a loop calculation in R

I have 10 variable X1,X2,..X10

> X1

[1] 11.388245  3.847984  3.271024  3.637894

> X2

[1]  3.603660  3.176091 20.868740  4.229564  3.150181  3.379059 11.379710  3.577636  5.094401

> X10

 [1] 11.613462  7.360181  3.210812  5.066974  5.391218  3.049254 10.639178  4.154140 

 [9]  3.502896  7.919751  3.416924  6.577095  5.047722  3.953996  3.153649  3.005215

ms<-list()

for (i in c(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10)){

  n<-length(i)

  m<-n/sum(log(i/3))

  ls<-c(ms,m)
}

the above R code does not work. what I want is to get final result with a numeric variable ms that contain 10 vaules from calculaing n/sum(log(i/3).

For example one of the value:

> n<-length(X1)

> m<-n/sum(log(X1/3))
> 
> m
[1] 2.148009

after apply X1, X2,..X10 in the loop to get:

 Ms <-(m1 m2 m3 ...m10)

Upvotes: 1

Views: 38

Answers (2)

A. Suliman
A. Suliman

Reputation: 13125

Here a MWE

ms <- c()
#to define ms in more efficient way use 
#ms <- vector("double", 10)
for(i in seq_len(10)){
           #use get to retrive an object from the global Environment 
           n<-length(get(paste0('X',i)))
           m<-n/sum(log(get(paste0('X',i))/3))
           ms[i]=m
           }

Upvotes: 0

Greg Snow
Greg Snow

Reputation: 49640

The c function is concatenating your vectors into 1 long vector, e.g. c(1:3, 5:7) will be 1 vector with 6 elements.

I think what you want is to use list instead of c which will keep the vectors as individual vectors.

Your for look should work if you do something like:

ms<-list()

for (i in list(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10)){

  n<-length(i)

  m<-n/sum(log(i/3))

  ms<-c(ms,m)
}

Note the fix to the last line.

But since the goal is to create a new list with the results, using the lapply function may be simpler:

ms <- lapply( list(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10), 
  function(x) length(x)/sum(log(x/3)) 
)

Upvotes: 1

Related Questions