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))
Amateur
source share