Cory Smith
Cory Smith

Reputation: 5

Counting instances of an event in a dataframe

Here is a toy example of how I'm trying to manipulate my data, I just can't get it to do what I need:

id <- c(1,2,3,1,4,5,2,1,6,7,8,8,9,6,4,7)
color <- c('red','blue','green','blue','yellow','blue','green','blue','green',
                 'red','blue','yellow','purple','blue','purple','green')

##What it currently looks like
df <- data.frame(id,color)

##what it needs to look like
id2 <- c(1,2,3,4,5,6,7,8,9)
color1 <- c('red','blue','green','yellow','blue','green',
            'red','blue','purple')
color2 <- c('blue','green',NA,'purple',NA,'blue','green','yellow',NA)
color3 <- c('blue',NA,NA,NA,NA,NA,NA,NA,NA)

df1 <- data.frame(id2,color1,color2,color3)

I struggled with an explanation, but think the example helps show what I need to do. Please let me know if there is any additional information needed.

Upvotes: 0

Views: 26

Answers (1)

Onyambu
Onyambu

Reputation: 79338

In base R you could do:

reshape(transform(df,time = ave(id, id, FUN = seq_along)), dir='wide', sep = '')

   id color1 color2 color3
1   1    red   blue   blue
2   2   blue  green   <NA>
3   3  green   <NA>   <NA>
5   4 yellow purple   <NA>
6   5   blue   <NA>   <NA>
9   6  green   blue   <NA>
10  7    red  green   <NA>
11  8   blue yellow   <NA>
13  9 purple   <NA>   <NA>

Upvotes: 1

Related Questions