Problem with na.rm with %>%

Hi, I don't know why when I try to use "na.rm = T " with "%>%" this code gives me an error but in"$" version its OK

example <- data.frame (var1 = c ("ITA", "AUT", "POR", "USA"),                      
                       var2 = c(1, 5, NA, 16))

mean(example$var2, na.rm = T)

example %>% 
  mean(var2, na.rm = T)

The first operation its fine but the second it doesn´t work

this code is equivalent to

  mean(example,var2, na.rm = T)

which gives an error rather than a warning but is clearly problematic
the direct analogy to mean(example$var2, na.rm = T) using %>% would be

example$var2 %>% mean( na.rm = T)
1 Like

You can use with( ) from base R or the exposition pipe, %$%, from the magrittr package. They will let the mean( ) function look in the piped data.frame for the variable.


example <- data.frame (var1 = c ("ITA", "AUT", "POR", "USA"),                      
                       var2 = c(1, 5, NA, 16))

example %>% with(mean(var2, na.rm = TRUE)) 
#> [1] 7.333333

example %$% mean(var2, na.rm = TRUE) 
#> [1] 7.333333

Created on 2023-01-10 with reprex v2.0.2

You can also do this:

example %>%  summarise (m = mean(var2, na.rm = T))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.