Loop through the dataframe list in R and apply if the else function

I have a dataframe list and would like to apply if else works through a list

df1= data.frame(letter=LETTERS[1:5], res=runif(10), cens=rep(0:1,5)) df2= data.frame(letter=LETTERS[1:5], res=runif(10), cens=rep(0,5)) df3= data.frame(letter=LETTERS[1:5], res=runif(10), cens=rep(0:1,5)) df4= data.frame(letter=LETTERS[1:5], res=runif(10), cens=rep(0,5)) df.list=list(df1,df2,df3,df4) reg.stats = function(var1){ gm.reg=exp(mean(log(var1))) gsd.reg=exp(sd(log(var1))) return(c(gm.reg,gsd.reg)) } other.stats = function(obs,cens){ nondetects <- obs[cens==1] detects <- obs[cens== 0] gm.other=exp(mean(log(detects))) gsd.other=exp(sd(log(detects))) return(c(gm.other,gsd.other)) } 

I would like to go through each df, and if the sum of the cens variable is in a separate df = 0 (i.e. df2), use the reg.stats function, otherwise use the other.stats function.

In a real data set, I have a list of 50 + dfs, and what I did in the past was to manually select dfs, where all cens = 0 and use the lapply function. That was fine, but if I split the data and use lapply separately for each list and then combine the results, the order changes and then I need to change the order of the result. Is there a faster and cleaner way to do this?

  uncens.list = df.list[c(2,4)] uncens.res= lapply(uncens.list, function(i) reg.stats(i$res)) cens.list = df.list[c(1,3)] cens.res.=lapply(cens.list,function(i) other.stats(i$res,i$cens)) 
+7
source share
2 answers

It works with if and else , but not with ifelse , since the latter returns only the first value of the result of the function:

 lapply(df.list, function(i) if (sum(i$cens) == 0) reg.stats(i$res) else other.stats(i$res,i$cens)) 

Result:

 [[1]] [1] 0.402693 1.467128 [[2]] [1] 0.3427096 2.4269668 [[3]] [1] 0.3731172 1.8051164 [[4]] [1] 0.3883753 2.0028039 

By the way: no need for separate functions. All this can be done in one command:

 lapply(df.list, function(i) {detects <- log(i$res[i$cens == 0]) c(exp(mean(detects)), exp(sd(detects)))}) 
+6
source

Have you looked at the package: plyr? http://cran.r-project.org/web/packages/plyr/index.html

In particular, the llply function?

If you wrote a wrapper function to determine which statistic function to call, given the value of cens, then it looks like you can invoke llply using a wrapper function.

0
source

All Articles