Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using dplyr package in R

Tags:

r

dplyr

I am using the below code to extract the summary of data with respect to column x by counting the values in column x from the dataset unique_data and arranging the count values in descending order.

unique_data %>%
group_by(x) %>%
arrange(desc(count(x)))

But, when I execute the above code i am getting the error message as below,

Error: no applicable method for 'group_by_' applied to an object of class "character"

Kindly, let me know as what is going wrong in my code. For your information the column x is of character data type.

Regards,
Mohan

like image 363
Mohan Raj Avatar asked Dec 15 '22 03:12

Mohan Raj


1 Answers

The reason is the wrapping of arrange on count. We need to do this separately. If we use the same code as in the OP's post, just split up the count and arrange step in two separate pipes. The output of count is a frequency column 'n' (by default), which we arrange in descending (desc) order.

unique_data %>% 
          group_by(x) %>% 
          count(x) %>%
          arrange(desc(n))

also the group_by is not needed. According to the ?count documentation

tally is a convenient wrapper for summarise that will either call n or sum(n) depending on whether you're tallying for the first time, or re-tallying. count() is similar, but also does the group_by for you.

So based on that, we can just do

count(unique_data, x) %>%
          arrange(desc(n))
like image 192
akrun Avatar answered Jan 02 '23 19:01

akrun