Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

r - Summarise does not accept counts()

I am creating a summary data frame for multiple columns with dplyr, and it works well for desired functions excepts for count or n(). I want to show total number of observations.

 summ <- Test_data %>%            
   summarize(across(
     .cols = is.numeric,
     .fns = list(a=n(),mean=mean, stdev=sd, max=max,min=min), na.rm=TRUE,
     .names = "{col}_{fn}"
   ))

It gives error: Error: Problem with summarise() input ..1.x Can't convert an integer vector to function i Input ..1 is across(...).

Why just function for counts does not work, please advise.

question from:https://stackoverflow.com/questions/65924698/summarise-does-not-accept-counts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @tjebo comments, n() is tricky inside of a summarize().

This is discussed the comment he linked - summarize_all with "n()" function - where @akrun explains "getting the n() for each column is not making much sense as it would be the same [for each summarized column]." The reason n() is giving you problems is because n() doesn't take any arguments, but the summarize is sending the value of the selected .cols as an argument.

Two solutions are to replace with the length function, or add a leading ~ to turn n() into ~ n(). (However, I don't know why ~ n() works, is it turning the code into a single-sided formulae? )

Also, use where(is.numeric) in the column selection.

iris %>% 
    summarize(across(.cols  = where(is.numeric), 
                     .fns   = list(n = ~ n(), mean = mean, sd = sd), 
                     .names = "{col}_{fn}"))

iris %>% 
    summarize(across(.cols  = where(is.numeric), 
                     .fns   = list(n = length, mean = mean, sd = sd), 
                     .names = "{col}_{fn}"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...