How do I change the following table from:
Type Name Answer n
TypeA Apple Yes 5
TypeA Apple No 10
TypeA Apple DK 8
TypeA Apple NA 20
TypeA Orange Yes 6
TypeA Orange No 11
TypeA Orange DK 8
TypeA Orange NA 23
Change to:
Type Name Yes No DK NA
TypeA Apple 5 10 8 20
TypeA Orange 6 11 8 23
I used the following codes to get the first table.
df_1 <-
df %>%
group_by(Type, Name, Answer) %>%
tally()
Then I tried to use the spread command to get to the 2nd table, but I got the following error message:
"Error: All columns must be named"
df_2 <- spread(df_1, Answer)
Following on the comment from ayk, I'm providing an example. It looks to me like when you have a data_frame with a column of either a factor or character class that has values of NA, this cannot be spread without either removing them or re-classifying the data. This is specific to a data_frame (note the dplyr class with the underscore in the name), as this works in my example when you have values of NA in a data.frame. For example, a slightly modified version of the example above:
Here is the dataframe
Which gives a data_frame that looks like this
Then, when we try to tidy it, we get an error message:
But if we remove the NA's then it 'works':
However, removing the NAs may not give you the desired result: i.e. you might want those to be included in your tidied table. You could modify the data directly to change the NAs to a more descriptive value. Alternatively, you could change your data to a data.frame and then it spreads just fine:
I think only tidyr is needed to get from
df_1
todf_2
.Output: