3

I have my data frame:

Name Time Event Serg 15 Log1 Nate 15 Log2 Serg 10 Log3 Nate 9 Log1 Nate 20 Log5 

And I want to transpose it by time for every Name by time like this:

Name 1 2 3 Serg Log3 Log1 NA Nate Log1 Log2 Log5 

Hope I explained clearly! Thanks

2
  • in your desider output, for row named Serg did your pick Log3 asthe first value by accident or on purpose? Commented Jan 23, 2017 at 20:52
  • never mind I see the pattern Commented Jan 23, 2017 at 20:52

1 Answer 1

4

We can use dcast from data.table. Convert the 'data.frame' to 'data.table' (setDT(df1)), then dcast the dataset to 'wide' format by creating a sequence id (rowid - from data.table does that for the 'Name' variable), pass it on the formula, and specify the value.var as "Event"

library(data.table) dcast(setDT(df1)[order(Name, Time)], Name ~ rowid(Name), value.var = "Event") # Name 1 2 3 #1: Nate Log1 Log2 Log5 #2: Serg Log3 Log1 NA 

Or using tidyverse

library(dplyr) library(tidyr) df1 %>% group_by(Name) %>% arrange(Name, Time) %>% mutate(ind = row_number()) %>% select(-Time) %>% spread(ind, Event) # Name `1` `2` `3` #* <chr> <chr> <chr> <chr> #1 Nate Log1 Log2 Log5 #2 Serg Log3 Log1 <NA> 
Sign up to request clarification or add additional context in comments.

2 Comments

Output isn't correct because in name Serg Log3 must be in the first column because its time is less than Log1 has.
@Smasell The output is corrected. Sorry, didn't check the order before

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.