How to make new columns by counting up an existing column

荒凉一梦 提交于 2019-12-24 00:40:00

问题


I'd like to make some other columns by doing group_by in R.

When the original table is like below

 userID   cat1    cat2
    a        f       3
    a        f       3
    a        u       1
    a        m       1
    b        u       2
    b        m       1
    b        m       2

I group them by userID and want it come like

userID   cat1_f  cat1_m  cat1_u  cat2_1  cat2_2  cat2_3
a        2       1       1       2       0       1
b        0       2       1       1       2       0

回答1:


We could gather all the values then count them, create a new column by pasteing cat and value values and then spread it back to wide format with fill=0.

library(tidyverse)

df %>%
  gather(cat, value, -userID) %>%
  count(userID, cat, value) %>%
  unite(cat, c(cat, value)) %>%
  spread(cat, n, fill = 0)

#  userID cat1_f cat1_m cat1_u cat2_1 cat2_2 cat2_3
#  <fct>   <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
#1  a          2      1      1      2      0      2
#2  b          0      2      1      1      2      0



回答2:


We can just use table from base R

table(df)
#       cat1
#userID f m u
#     a 2 1 1
#     b 0 2 1

Or with dcast from data.table

library(data.table)
dcast(setDT(df), userID ~ paste0('cat1_', cat1))

data

df <- structure(list(userID = c("a", "a", "a", "a", "b", "b", "b"), 
cat1 = c("f", "f", "u", "m", "u", "m", "m")), class = "data.frame", 
 row.names = c(NA, -7L))


来源:https://stackoverflow.com/questions/54510200/how-to-make-new-columns-by-counting-up-an-existing-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!