0
votes

I have a data frame like the one generated below. The id column is not unique I also have a data frame of 365 columns, one for each day. The "day" column represents the day of the year. I would like each row of the second data frame to map to the id column with 1s for the days that are present with that id and 0s otherwise. The data are not ordered neatly like in the example data frame.

data <- data.frame(id = 1:100, day = as.integer(runif(100, 0, 364)))

The expected output for an id that had the values 0, 3, and 364 in the original data frame would be:

    id day0 day1 day2 day3 ... day364
     1    1    0    0    1          1

I am also open to solutions that involve using data.table. Thank you!

2
I think you need reshape or dcast from the reshape2 package... but its very unclear what you want exactly. Can you make a reproducible example and include the whole desired output.Justin
Agree, I got lost a little bit in the explanation... can you please clarify a little bit more?nico
@Justin The desired output is listed -- I can't reproduce the example because I don't know how to generate the output. The data produced above will produce a data.frame similar to the one I'm working with. The desired output is a new data.frame that collapses across ids and generates a 1 if the value for that day is found in the original data.frame or 0 otherwise. What else can I provide to make this clearer?user836015
Note that as.integer(runif(n, 0, 364)) cannot result in 364. Use sample(0:364, n, replace=TRUE).Ferdinand.kraft
Sounds like you're just looking for with(data, table(id, day)).Thomas

2 Answers

0
votes

Per my comment, you just want a crosstable, which can be obtained with:

tab <- with(data,table(id, day))

If you just want that table to show presence/absence of matches (i.e., a cell should be 1 even if multiple entries correspond to the same id/day pair), then just convert tab with the following:

tab[tab>=1] <- 1
0
votes

Just for fun here's an alternate solution:

library(reshape2)
dcast(data, id ~ day, is.integer, fill =0)