在R中自定义lapply() [英] Customize lapply() in R

查看:70
本文介绍了在R中自定义lapply()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自定义 lapply(df,FUN =平均值)

这很好用

mtcars
means.mtcars <- lapply(mtcars, FUN = mean)

但是我想查看 prop.table(table(df $ column))并根据其不同级别将它们另存为另一行

but I want to see the prop.table(table(df$column)) and save them as a different row based on its different levels

mtcars$gear1 <- factor(mtcars$gear, levels = c(3,4,5))

my.mean <- function(df) {
   ifelse(is.numeric(df)== T, mean(df),
   ifelse(df$gear1 == 3, df$newColumn1 ==  as.data.frame(prop.table(table(df$gear1)))[1, "Freq"],
      ifelse( df$gear1 == 4, df$newColumn2 ==  as.data.frame(prop.table(table(df$gear1)))[2, "Freq"],
              df$newColumn3 == as.data.frame(prop.table(table(df$gear1)))[3, "Freq"]  )))
}

not.working <- lapply(mtcars, FUN = my.mean)

预期结果means.mtcars,最后是newColumn1,newColumn2,newColumn3

Expected results means.mtcars and at the end newColumn1,newColumn2,newColumn3

            V1
mpg   20.090625
cyl    6.187500
disp 230.721875
hp   146.687500
drat   3.596563
wt     3.217250
qsec  17.848750
vs     0.437500
am     0.406250
gear   3.687500
carb   2.812500
newColumn1  0.46875
newColumn2  0.37500
newColumn3  0.15625 

非常感谢

推荐答案

使用 lapply 时,您正在向数据框中的每个列单独应用一个函数.这里的问题是您希望将其中一列分成三部分,而 lapply 不能直接进行.但是,解决此问题很容易:

When you use lapply, you are applying a function to each column in isolation in your data frame. The problem here is that you want one of the columns split into three, which lapply doesn't do directly. However, it's easy to work around this:

my.mean <- function(x) if(is.numeric(x)) mean(x) else prop.table(table(x))
setNames(as.data.frame(unlist(lapply(mtcars, FUN = my.mean))), "mean")
#>               mean
#> mpg      20.090625
#> cyl       6.187500
#> disp    230.721875
#> hp      146.687500
#> drat      3.596563
#> wt        3.217250
#> qsec     17.848750
#> vs        0.437500
#> am        0.406250
#> gear      3.687500
#> carb      2.812500
#> gear1.3   0.468750
#> gear1.4   0.375000
#> gear1.5   0.156250

reprex软件包(v0.3.0)创建于2020-05-27 sup>

Created on 2020-05-27 by the reprex package (v0.3.0)

这篇关于在R中自定义lapply()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆