Preet Rajdeo
Preet Rajdeo

Reputation: 377

reshape variable by unique values in each id

Hi I've been trying to reshape my data to wide.

id story_id
1   123
1   123
1   123
1   123
2   213
2   213
2   213
3   123 
3   123
3   123

But all I get is:

id
1
2
3

I am using the code:

data=reshape(data, idvar="id", timevar="story_id", direction="wide")

The desired output is

id  story_id.123 story_id.213
1    123          NA
2    NA           213
3    123          NA

Please let me know what the problem is.

Upvotes: 0

Views: 201

Answers (2)

akrun
akrun

Reputation: 886938

Here is an option using spread

library(dplyr)
library(tidyr)
df1 %>% 
  distinct %>% 
  spread(story_id, story_id) %>% 
  setNames(., c(names(.)[1], paste0("story_id", names(.)[-1])))
#    id story_id123 story_id213
#1  1         123          NA
#2  2          NA         213
#3  3         123          NA

Upvotes: 0

MichaelChirico
MichaelChirico

Reputation: 34703

The following works:

library(data.table) ; setDT(DF)

dcast(unique(DF), id ~ story_id, value.var = "story_id")

Upvotes: 1

Related Questions