简体   繁体   中英

R tidyverse to sumif based on function

I have a df like this:

df1

var1 var2 text
1    0    A 
1    1    A
0    1    B

So I would like to generate a two new ones based on a sumif function like this:

df2

text var1   var2
A    2      1
B    0      1
tot  2      4

And...

df3

text var1   var2
A    100    50
B    0      50

So the first one based on counts and the second one on column %

Thx.

To get df2 :

library(dplyr)

df1 %>% group_by(text) %>% summarise_all(sum) %>% janitor::adorn_totals('row')

#  text var1 var2
#     A    2    1
#     B    0    1
# Total    2    2

df3

df1 %>% group_by(text) %>% summarise_all(sum) %>% mutate_at(-1, ~./sum(.) * 100)

#  text   var1  var2
#  <fct> <dbl> <dbl>
#1 A       100    50
#2 B         0    50

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM