简体   繁体   中英

Apply multiple functions within a single function to a DataFrame

I have currently written this code

X1<-c(8.7, 14.3, 18.9, 19.0, 20.5, 14.7, 18.8, 37.3, 12.6, 25.7)
X2<-c(0.3, 0.9, 1.8, 0.8, 0.9, 1.1, 2.5, 2.7, 1.3, 3.4)
X3<-c(3.1, 7.4, 9.0, 9.4, 8.3, 7.6, 12.6, 18.1, 5.9, 15.9)

df<-data.frame(x1=X1,x2=X2,x3=X3)

multi.fun <- function(x) {
  c(media = mean(x), desv.tip = sd(x), fischer = sum((x-mean(x))^3)/(nrow(df)*(sd(x))^3))
}

sapply(df, multi.fun)

With which I get:

                 x1        x2        x3
media    19.0500000 1.5700000 9.7300000
desv.tip  7.9560250 0.9967168 4.5660705
fischer   0.9549109 0.5209099 0.4954127

My question is if I can embed the 'sapply' function inside the 'multi.fun' function, in such a way to get a single function?

We can place the sapply inside the function and pass the dataset as argument

multi.fun <- function(dat) {
  sapply(dat, function(x) c(media = mean(x), desv.tip = sd(x), 
           fischer = sum((x-mean(x))^3)/(nrow(dat)*(sd(x))^3)))
  }

multi.fun(df)
#                 x1        x2        x3
#media    19.0500000 1.5700000 9.7300000
#desv.tip  7.9560250 0.9967168 4.5660705
#fischer   0.9549109 0.5209099 0.4954127

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM