Tpellirn
Tpellirn

Reputation: 796

How to apply a function to all columns in R?

I have a data.frame that look like

 res
  date        X0  X1  X3     car
   2000-01-01 167 185 187     A
   2000-01-01 167 185 187     A
   2000-01-01 167 185 187     A
   2000-01-01 167 185 187     A
   2001-01-01 169 186 187     N
   2001-01-01 169 186 187     N
   2001-01-01 169 186 187     N
   2001-01-01 169 186 187     N

This will compute the mean or any function for X0:

res %>%
     group_by(car) %>% 
          summarise(Myres= mean(X0))

How can I apply this to all columns except "date"

Upvotes: 1

Views: 383

Answers (3)

akrun
akrun

Reputation: 886938

An option with collapse

library(collapse)    
fmean(res[2:4], GRP(res, ~ car))
#    X0  X1  X3
#A 167 185 187
#N 169 186 187

Or as @G.Grothendieck mentioned, collap can be used

collap(res[-1], ~ car, fmean)

Or as

collap(slt(res, X0:X3), res$car)

where slt is shortcut for fselect and collap is a fast and easy to use multi-purpose data aggregation command (as per documentation)


If we want to pass sens.slope and extract some components, apply the function as a lambda function

library(trend)
collap(res[-1], ~ car, FUN =  function(x) sens.slope(x)$estimates)

data

res <- structure(list(date = c("2000-01-01", "2000-01-01", "2000-01-01", 
"2000-01-01", "2001-01-01", "2001-01-01", "2001-01-01", "2001-01-01"
), X0 = c(167L, 167L, 167L, 167L, 169L, 169L, 169L, 169L), X1 = c(185L, 
185L, 185L, 185L, 186L, 186L, 186L, 186L), X3 = c(187L, 187L, 
187L, 187L, 187L, 187L, 187L, 187L), car = c("A", "A", "A", "A", 
"N", "N", "N", "N")), class = "data.frame", row.names = c(NA, 
-8L))

Upvotes: 1

Anoushiravan R
Anoushiravan R

Reputation: 21908

Maybe if you share a reproducible excerpt of your data we can help you better, but in general you can use summarise_if function of dplyr package for this purpose:

library(lubridate)
res %>% group_by(car) %>% summarise_if(!is.Date, mean)

this might help because I got the similar results from the following code on iris data:

> iris %>% group_by(Species) %>% summarise_if(is.double, mean)
# A tibble: 3 x 5
  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
1 setosa             5.01        3.43         1.46       0.246
2 versicolor         5.94        2.77         4.26       1.33 
3 virginica          6.59        2.97         5.55       2.03 

Upvotes: 2

Matt Kaye
Matt Kaye

Reputation: 520

For this, you can do:

res %>%
  group_by(car) %>%
  summarize(across(-c(date), mean)

This says "apply the function mean to every column except for date, grouped by car

Upvotes: 5

Related Questions