-1

我有一个名为 my_df 的数据框,其中包含以下信息:

Id_user Id_log Condition
123     a      day
124     a      day
125     a      night
126     b      day
127     b      day
130     c      night

我想根据 Id_log 出现的次数创建一个新列。例如:

Id_user Id_log Condition Id_log_user
123     a      day       1
124     a      day       2
125     a      night     3
126     b      day       1
127     b      day       2
130     c      night     1

我试过的是用dplyr函数计数:

counts_id_log<-my_df %>% group_by(id_log) %>% count(id_log)

counts_id_log 看起来像:

id_log n
a      3
b      2
c      1

然后我可以使用 id_log 作为向量,然后根据 id_log 的值创建一个升序数字向量。例如:

x<- counts_id_log$n

基于 x 我正在尝试创建以下向量:

y<- c(1,2,3,1,2,1)

之后,我可以将 y 向量添加到原始数据框中。我尝试了一些东西rep,但没有好的结果。任何建议将不胜感激。我希望这很清楚。

4

3 回答 3

2

如果我理解正确,您可以执行以下操作

x <- c(2,2,4,5,1,2,3,5)

unlist(sapply(x, function(x) 1:x))
# [1] 1 2 1 2 1 2 3 4 1 2 3 4 5 1 1 2 1 2 3 1 2 3 4 5

或避免显式function

unlist(sapply(x, seq, from = 1))

identical(as.numeric(unlist(sapply(x, function(x) 1:x))), y)
#[1] TRUE
于 2019-02-26T01:41:53.620 回答
0

修改后

library(dplyr)
df%>%group_by(Id_log)%>%mutate(Id_log_user=row_number())
于 2019-02-26T01:54:21.817 回答
0

使用这个自定义函数,它应该做你想做的事:

CountNumber <- function(x) ave(seq_along(x), x, FUN=seq_along) 
my_df$count <- CountNumber(my_df$Id_log)

我之前问过这个问题,有人向我提供了这个答案,但我找不到要归功于的原件。

于 2019-02-26T02:32:45.940 回答