gpt4 book ai didi

r - 循环遍历 R 中的数据帧列表并应用 if else 函数

转载 作者:行者123 更新时间:2023-12-04 10:08:07 29 4
gpt4 key购买 nike

我有一个数据框列表,如果其他功能通过列表,我想应用

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 中的 cens 变量的总和 = 0(即 df2),则应用 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)))})

关于r - 循环遍历 R 中的数据帧列表并应用 if else 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13845249/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com