0

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

df = data.frame(id = 1:10, assignment= c("B","A","B","B","B","A","B","B","A","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”)?谢谢

4

3 回答 3

2

使用lapplyoveruniqueassignment来创建新列。

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
于 2021-02-16T09:40:48.610 回答
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
于 2021-02-16T23:19:40.987 回答
1

我们可以model.matrix使用colCumsums

library(matrixStats)
cbind(df, colCumsums(model.matrix(~ assignment - 1, df[-1])))
于 2021-02-16T23:07:37.960 回答