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
352 views
in Technique[技术] by (71.8m points)

r - How to apply janitor::tabyl to several columns on data table?

I have a dataframe:

ID   value    value_type
A    256       new
B    543       new
A    544       old

I want to apply janitor::tabyl to columns ID and value_type to get:

ID
     n    percent
A    2     0.66
B    1     0.33


value_type

       n    percent
new    2     0.66
old    1     0.33

How could I do that? When I do:

janitor::tabyl(dt[, c(ID, value_type)])

it doesn't separate those statistic tables by column

question from:https://stackoverflow.com/questions/65904779/how-to-apply-janitortabyl-to-several-columns-on-data-table

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

1 Reply

0 votes
by (71.8m points)
library(purrr)
library(dplyr)

df %>% map(., ~tabyl(.))

You could select the columns you need:

df %>% 
  select(ID, value_type) %>% 
  map(., ~tabyl(.))

This gives us:

$ID
 . n   percent
 A 2 0.6666667
 B 1 0.3333333

$value_type
   . n   percent
 new 2 0.6666667
 old 1 0.3333333

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

...