如何通过向上计数的现有列,使新列

问题描述 投票:2回答:2

我想在做R.向GROUP_BY让一些列

当原来的表像之下

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

我集团通过他们的用户ID,并希望它来像

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
r dataframe group-by dplyr
2个回答
2
投票

我们可以gather所有的值,那么count他们,通过pasteing catvalue值创建一个新的列,然后spread回用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

1
投票

我们刚刚从table使用base R

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

或者与来自dcast 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))
© www.soinside.com 2019 - 2024. All rights reserved.