如何用 plyr 包中 count 函数的结果替换原始数据?

How to substitute the original data with the results from the count function from the plyr package?

我的原始数据是这样的:

  x1 x2 x3
1  0  0  0
2  1  1  1
3  1  1  1
4  1  3  1
5  2  2  2
6  3  3  3
7  3  3  3
8  3  2  2

使用 plyr 包中的计数函数后,结果将如下所示:

 x1 x2 x3 freq
1  0  0  0    1
2  1  1  1    2
3  1  3  1    1
4  2  2  2    1
5  3  2  2    1
6  3  3  3    2

如何将原始数据 table 替换为这样的数据?:

  x1 
1  1  
2  2  
3  2  
4  3  
5  4 
6  6  
7  6  
8  5

你可以试试

df1$x1 <- as.numeric(factor(rowSums(df1)))
df1$x1
#[1] 1 2 2 3 4 6 6 5

或使用 plyr

中的 count
library(plyr)
df2 <- count(df1)
freq1 <- df2$freq
df1$x1 <- join(unique(df1),transform(join(df2, df1), 
               new=rep(seq_along(freq1), freq1)))$new

df1$x1
#[1] 1 2 2 3 4 6 6 5

数据

df1 <- structure(list(x1 = c(0L, 1L, 1L, 1L, 2L, 3L, 3L, 3L), 
x2 = c(0L, 1L, 1L, 3L, 2L, 3L, 3L, 2L), x3 = c(0L, 1L, 1L, 1L, 2L, 3L, 
3L, 2L)), .Names = c("x1", "x2", "x3"), class = "data.frame", 
row.names = c("1", "2", "3", "4", "5", "6", "7", "8"))