Problem
I have a data frame that looks like this:
ID User.Food matched.indexes
1 1 milk 2, 8, 15
2 2 apples
3 3 bread 4, 6
4 4 ice cream 5
5 5 boxed fruits
The matched.indexes
column contains a vector of integers. I want to convert this into long format so each matched index is on one row:
ID User.Food matched.indexes
1 1 milk 2
2 1 milk 8
3 1 milk 15
4 2 apples NA
5 3 bread 4
6 3 bread 6
7 4 ice cream 5
8 5 boxed fruits NA
All of the questions and tutorials I have seen focus on changing a wide data frame with multiple named columns into long format (melt
, gather
, etc) or on separating out a cell that holds a string "2, 8, 15"
, but with this I am unclear on how to unpack the vector within the matched.indexes
column?
Data
This data frame comes from the results of using agrep
to get possible matches from a food groups data frame. Code to reproduce it is below:
df1 <- structure(list(ID = 1:5,
User.Food = c("milk", "apples", "bread", "ice cream",
"boxed fruits"),
matched.indexes = list(c(2, 8, 15), NA, c(4,6), c(5),
NA)),
.Names = c("ID", "User.Food", "matched.indexes"),
class = "data.frame",
row.names = c("1", "2", "3", "4", "5"))