-1

I have a data frame named my_df with the following information:

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

I would like to make a new column with values based on the number of times Id_log appears. For example:

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

What I've tried is making a count with dplyr functions:

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

counts_id_log looks like:

id_log n
a      3
b      2
c      1

Then I can use id_log as a vector and then create a vector of ascending numbers based on the value of id_log. For example:

x<- counts_id_log$n

Based on x I am trying to create the following vector:

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

After tha I can add y vector to the original data frame. I've tried something rep but without good results. Any suggestion would be appreciated. I hope this is clear.

3 Answers3

2

Provided I understood you correctly, you can do the following

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

or avoiding the explicit function

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

identical(as.numeric(unlist(sapply(x, function(x) 1:x))), y)
#[1] TRUE
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

After you modified

library(dplyr)
df%>%group_by(Id_log)%>%mutate(Id_log_user=row_number())
BENY
  • 317,841
  • 20
  • 164
  • 234
0

Use this custom function and it should do what you want:

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

I asked this question previously and somebody provided me this answer but I can't find the original to credit.

Roasty247
  • 679
  • 5
  • 20