根据一列的类别创建两列累积总和

问题描述

我喜欢在作业列中创建两个累积频率为“A”和“B”的列。

df = data.frame(id = 1:10,assignment= c("B","A","B","B"))

            id assignment
        1   1          B
        2   2          A
        3   3          B
        4   4          B
        5   5          B
        6   6          A
        7   7          B
        8   8          B
        9   9          A
        10 10          B

结果表将具有这种格式

            id  assignment  A   B
        1   1   B           0   1
        2   2   A           1   1
        3   3   B           1   2
        4   4   B           1   3
        5   5   B           1   4
        6   6   A           2   4
        7   7   B           2   5
        8   8   B           2   6
        9   9   A           3   6
       10   10  B           3   7

如何概括超过 2 个类别的代码(比如“A”、“B”、“C”)? 谢谢

解决方法

使用 lapply 超过 unique 中的 assignment 值来创建新列。

vals <- sort(unique(df$assignment))
df[vals] <- lapply(vals,function(x) cumsum(df$assignment == x))
df

#   id assignment A B
#1   1          B 0 1
#2   2          A 1 1
#3   3          B 1 2
#4   4          B 1 3
#5   5          B 1 4
#6   6          A 2 4
#7   7          B 2 5
#8   8          B 2 6
#9   9          A 3 6
#10 10          B 3 7
,

我们可以将 model.matrixcolCumsums 一起使用

library(matrixStats)
cbind(df,colCumsums(model.matrix(~ assignment - 1,df[-1])))
,

基本的 R 选项

transform(
  df,A = cumsum(assignment == "A"),B = cumsum(assignment == "B")
)

给予

   id assignment A B
1   1          B 0 1
2   2          A 1 1
3   3          B 1 2
4   4          B 1 3
5   5          B 1 4
6   6          A 2 4
7   7          B 2 5
8   8          B 2 6
9   9          A 3 6
10 10          B 3 7

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...