df <- data.frame(animal = c("dog", "dog", "cat", "dog", "cat", "cat"),
hunger = c(0, 1, 1, 0, 1,1))
I have a dataframe like the one above with two columns, one containing categories and the other containing binary data.
I am looking to reshape the dataframe to split the category ("animal") column up into two columns of its own with the values of "animal" column as column names and the values of the other column (hunger) as cell values, i.e.
Desired output:
df <- data.frame(dog = c(0, 1, 0),
cat = c(1, 1, 1))
How can I achieve this?
In the case of uneven length among different categories, we can use
list2DF(
lapply(
. <- unstack(df, hunger ~ animal),
`length<-`,
max(lengths(.))
)
)
or
list2DF(
lapply(
. <- unstack(rev(df)),
`length<-`,
max(lengths(.))
)
)
and we will obtain
cat dog
1 1 0
2 1 1
3 1 0
4 0 NA
Dummy data
df <- data.frame(
animal = c("dog", "dog", "cat", "dog", "cat", "cat", "cat"),
hunger = c(0, 1, 1, 0, 1, 1, 0)
)
We can also use unstack, e.g.,
> unstack(rev(df))
cat dog
1 1 0
2 1 1
3 1 0
or
> unstack(df, hunger ~ animal)
cat dog
1 1 0
2 1 1
3 1 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With