如何一次在数据框列上应用不同的函数

问题描述 投票:-1回答:2

我想将不同的函数应用于数据框的列。目前,我正在逐一进行。作为一个例子,我已经提出了一些可重现的代码。

col1_mean <- mean(iris$Sepal.Length)
col2_mean <- mean(iris$Sepal.Width)
.
.    

col1_median <- median(iris$Sepal.Length)
col2_median <- median(iris$Sepal.Width)
.
.

col1_sd <- sd(iris$Sepal.Length)
col2_sd <- sd(iris$Sepal.Width)
.
.

我怎么能一步到位呢?

r function dataframe
2个回答
1
投票

我们可以做点什么

multiple_funs <- function(x){
  c(mean = mean(x), median = median(x), sd = sd(x))
}
sapply(iris[, -5], multiple_funs)

#           Sepal.Length Sepal.Width Petal.Length Petal.Width
# mean      5.8433333   3.0573333     3.758000   1.1993333
# median    5.8000000   3.0000000     4.350000   1.3000000
# sd        0.8280661   0.4358663     1.765298   0.7622377

或者plyr::each()

multiple_funs <- plyr::each(mean, median, sd)
sapply(iris[,-5], multiple_funs)


#           Sepal.Length Sepal.Width Petal.Length Petal.Width
# mean      5.8433333   3.0573333     3.758000   1.1993333
# median    5.8000000   3.0000000     4.350000   1.3000000
# sd        0.8280661   0.4358663     1.765298   0.7622377

1
投票
> A=aggregate(.~1,iris[-5],function(x){c(mean=mean(x),median=median(x),sd=sd(x))})
> `row.names<-`(do.call(rbind,A),names(iris[-5]))
                 mean median        sd
Sepal.Length 5.843333   5.80 0.8280661
Sepal.Width  3.057333   3.00 0.4358663
Petal.Length 3.758000   4.35 1.7652982
Petal.Width  1.199333   1.30 0.7622377
© www.soinside.com 2019 - 2024. All rights reserved.