簡體   English   中英

循環遍歷R中的數據幀列表並應用if else函數

[英]loop through a list of dataframe in R and apply if else function

我有一個數據框列表,並希望通過列表應用if else函數

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))
 }

我想循環遍歷每個df,如果單個df = 0(即df2)中的cens變量之和,則應用reg.stats函數,否則應用other.stats函數。

在真實數據集中,我有一個50多個dfs的列表,我過去做的是手動挑選所有cens = 0的dfs並使用lapply函數。 沒關系,但如果我將數據框分開並為每個列表單獨使用lapply然后合並結果,則更改順序,然后我需要重新排序結果。 有更快,更清潔的方法嗎?

  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))

它適用於ifelse但不適用於ifelse因為后者只返回函數結果的第一個值:

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

結果:

[[1]]
[1] 0.402693 1.467128

[[2]]
[1] 0.3427096 2.4269668

[[3]]
[1] 0.3731172 1.8051164

[[4]]
[1] 0.3883753 2.0028039

順便說一下:不需要單獨的功能。 它可以在一個命令中完成:

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

你看過包裝了嗎?plyr? http://cran.r-project.org/web/packages/plyr/index.html

具體來說,功能llply?

如果您編寫了一個包裝器函數來確定在給定cens的值的情況下調用哪些stats函數,那么您似乎可以使用包裝器函數調用llply。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM