0

I've successfully created a table and summary of the data, but how can I extract the means from the table? (mean(VeryActiveminutes), mean(FairlyActiveMinutes), etc.). Is there something I can add to the summary function?

totalTime <- Activity %>% 
  select(VeryActiveMinutes, FairlyActiveMinutes, LightlyActiveMinutes, SedentaryMinutes) %>% 
  summary()

(https://i.stack.imgur.com/XuaiA.png)

I've tried using mean(), but unable to inside a table. I've also tried summing the values of each dataset,

AvgVeryActiveMinutes=sum(VeryActiveMinutes$VeryActiveMinutes)/nrow(VeryActiveMinutes)

but that seems quite repetitive.

L Tyrone
  • 1,268
  • 3
  • 15
  • 24

2 Answers2

0

summary here does a lot of things, it's actually a method and dispatches to summary.data.frame in this case.

If you want the mean of specific columns of a data frame, you can use mean in an lapply. Here demonstrated on the mtcars dataset that comes with R:

lapply(X=mtcars[c('mpg', 'cyl', 'disp')], FUN=mean)
# $mpg
# [1] 20.09062
# 
# $cyl
# [1] 6.1875
# 
# $disp
# [1] 230.7219
jay.sf
  • 60,139
  • 8
  • 53
  • 110
0

mean expects a vector as input. For vectorized mean operations, select the columns and use colMeans from base R

nm1 <- c("VeryActiveMinutes", "FairlyActiveMinutes",
  "LightlyActiveMinutes", "SedentaryMinutes")
colMeans(Activity[nm1],  na.rm = TRUE)

For the tidyverse, mean can be applied within across

library(dplyr)
Activity %>%
   summarise(across(all_of(nm1), ~ mean(.x, na.rm = TRUE)))
akrun
  • 874,273
  • 37
  • 540
  • 662