14

我有一个看起来像这样的数据集,其中一列可以有四个不同的值:

dataset <- data.frame(out = c("a","b","c","a","d","b","c","a","d","b","c","a"))

在 R 中,我想创建第二列,按顺序记录包含特定值的累积行数。因此输出列将如下所示:

out
1
1
1
2
1
2
2
3
2
3
3
4
4

2 回答 2

18

试试这个:

dataset <- data.frame(out = c("a","b","c","a","d","b","c","a","d","b","c","a"))
with(dataset, ave(as.character(out), out, FUN = seq_along))
# [1] "1" "1" "1" "2" "1" "2" "2" "3" "2" "3" "3" "4"

当然,您可以data.frame使用类似的方法将输出分配给您的列out$asNumbers <- with(dataset, ave(as.character(out), out, FUN = seq_along))

更新

“dplyr”方法也很不错。逻辑与“data.table”方法非常相似。一个优点是您不需要包装上述方法as.numeric所需的输出ave

dataset %>% group_by(out) %>% mutate(count = sequence(n()))
# Source: local data frame [12 x 2]
# Groups: out
# 
#    out count
# 1    a     1
# 2    b     1
# 3    c     1
# 4    a     2
# 5    d     1
# 6    b     2
# 7    c     2
# 8    a     3
# 9    d     2
# 10   b     3
# 11   c     3
# 12   a     4

第三种选择是getanID从我的“splitstackshape”包中使用。对于这个特定示例,您只需要指定data.frame名称(因为它是单个列),但是,通常,您会更具体并提及当前用作“ids”的列,并且该函数将检查是否它们是唯一的,或者是否需要累积序列才能使它们唯一。

library(splitstackshape)
# getanID(dataset, "out")  ## Example of being specific about column to use
getanID(dataset)
#     out .id
#  1:   a   1
#  2:   b   1
#  3:   c   1
#  4:   a   2
#  5:   d   1
#  6:   b   2
#  7:   c   2
#  8:   a   3
#  9:   d   2
# 10:   b   3
# 11:   c   3
# 12:   a   4
于 2013-03-05T17:39:46.553 回答
7

更新:

正如阿南达指出的那样,您可以使用更简单的:

 DT[, counts := sequence(.N), by = "V1"]

(其中DT如下)


您可以创建一个“计数”列,初始化为 1,然后按因子计算累积总和。下面是一个快速实现data.table

# Called the column V1
dataset<-data.frame(V1=c("a","b","c","a","d","b","c","a","d","b","c","a"))

library(data.table)

DT <- data.table(dataset)

DT[, counts := 1L]
DT[, counts := cumsum(counts), by=V1]; DT

#     V1 counts
#  1:  a      1
#  2:  b      1
#  3:  c      1
#  4:  a      2
#  5:  d      1
#  6:  b      2
#  7:  c      2
#  8:  a      3
#  9:  d      2
# 10:  b      3
# 11:  c      3
# 12:  a      4
于 2013-03-05T18:05:21.803 回答