A have the following tibble:
structure(list(age = c("21", "17", "32", "29", "15"),
gender = structure(c(2L, 1L, 1L, 2L, 2L), .Label = c("Female", "Male"), class = "factor")),
row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("age", "gender"))
age gender
<chr> <fctr>
1 21 Male
2 17 Female
3 32 Female
4 29 Male
5 15 Male
And I am trying to use tidyr::spread
to achieve this:
Female Male
1 NA 21
2 17 NA
3 32 NA
4 NA 29
5 NA 15
I thought spread(gender, age)
would work, but I get an error message saying:
Error: Duplicate identifiers for rows (2, 3), (1, 4, 5)
Right now you have two
age
values forFemale
and three forMale
, and no other variables keeping them from being collapsed into a single row, asspread
tries to do with values with similar/no index values:spread
doesn't apply a function to combine multiple values (à ladcast
), so rows must be indexed so there's one or zero values for a location, e.g.If you your values aren't indexed naturally by the other columns you can add a unique index column (e.g. by adding the row numbers as a column) which will stop
spread
from trying to collapse the rows:If you want to remove it afterwards, add on
select(-i)
. This doesn't produce a terribly useful data.frame in this case, but can be very useful in the midst of more complicated reshaping.