I'm trying to use pipes but I think something is wrong with my syntaxis. When I write:
mean(b_2021_01$Day.of.week, na.rm=TRUE)
Everything is ok, but when I write...
b_2021_01 %>% mean(Day.of.week, na.rm=T)
An error message appears "Warning message: In mean.default(., Day.of.week, na.rm = T) : argument is not numeric or logical: returning NA"
The "Day.of.week" variable is an int, I don't understand why it says that my argument is not numeric.
CodePudding user response:
Use pull
to extract the column and then use mean
library(magrittr)
b_2021_01 %>%
pull(Day.of.week) %>%
mean(na.rm = TRUE)
Or wrap with {}
b_2021_01 %>%
{mean(.$Day.of.week, na.rm=TRUE)}
Or use exposition operator (%$%
)
b_2021_01 %$%
mean(Day.of.week, na.rm = TRUE)
-testing
> mtcars %$%
mean(mpg, na.rm = TRUE)
[1] 20.09062
The reason for the error is the first argument x
should be a vector, but on the rhs of %>%
, it is taken as the whole data.frame as input
> mtcars %>% mean(.$mpg, na.rm = TRUE)
[1] NA
Warning message:
In mean.default(., .$mpg, na.rm = TRUE) :
argument is not numeric or logical: returning NA
> mean(mtcars, mtcars$mpg )
[1] NA
Warning message:
In mean.default(mtcars, mtcars$mpg) :
argument is not numeric or logical: returning NA