I would like to create a magrittr
pipe chain for the nested function call below
which produces the exact same output.
The following returns a data frame with columns my_names
and Freq
.
my_names <- c('John', 'Joe', 'Jane', 'John', 'John', 'Jane')
test_df <- as.data.frame.table(sort(table(my_names), decreasing = TRUE))
my_names Freq
1 John 3
2 Jane 2
3 Joe 1
Using magrittr
the pipe chain below returns a data frame with columns .
and Freq
library(magrittr)
test_df <- my_names %>% table %>% sort(decreasing = TRUE) %>% as.data.frame.table
. Freq
1 John 3
2 Jane 2
3 Joe 1
Adding %>% dplyr::rename(my_names = .)
won't work because .
is interpreted as the placeholder
and not as the column name.
To produce the same output as in the nested function call I need to use an additional function call: test_df <- dplyr::rename(test_df, my_names = .)
Is there a way to tell %>%
to interpret .
as a variable name and not as the placeholder in the subsequent call?
This is very, very late, but you can use the rename_
version (with the underscore) and the string "."
. This avoids nonstandard evaluation and hence works around %>%
substituting .
.
test_df <- my_names %>% table %>% sort(decreasing = TRUE) %>% as.data.frame.table %>%
rename_(my_names=".")
# my_names Freq
#1 John 3
#2 Jane 2
#3 Joe 1