Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape data to split column values into columns

Tags:

r

dplyr

reshape

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?

like image 843
Icewaffle Avatar asked Dec 09 '25 20:12

Icewaffle


1 Answers

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
like image 54
ThomasIsCoding Avatar answered Dec 12 '25 15:12

ThomasIsCoding