Home > other >  How do I convert a data frame with multiple variables in rows from wide to long in R?
How do I convert a data frame with multiple variables in rows from wide to long in R?

Time:11-18

I have a data frame that looks like:

Amount          person1  person2  person3 

pocketmoney     0.5        1.3     1.7

chores          3          5        2

How do I turn it into something like this:


Person     Pocketmoney   chores

person1         0.5         3

person2         1.3         5

person3         1.7         2


Thanks!

CodePudding user response:

Using tidyr:

> df1 %>% 
    pivot_longer(-Amount) %>% 
    pivot_wider(names_from = Amount, values_from = value) %>% 
    mutate(name = sub("\\D ", "", name)) # remove "person"
# A tibble: 3 × 3
  name  pocketmoney chores
  <chr>       <dbl>  <dbl>
1 1             0.5      3
2 2             1.3      5
3 3             1.7      2

CodePudding user response:

We may use data.table::transpose

library(data.table)
data.table::transpose(setDT(df1), make.names = "Amount",
    keep.names = 'Person')[]

-output

     Person pocketmoney chores
    <char>       <num>  <num>
1: person1         0.5      3
2: person2         1.3      5
3: person3         1.7      2

Or using base R

data.frame(Person = seq_along(df1[-1]), t(df1[-1]))

data

df1 <- structure(list(Amount = c("pocketmoney", "chores"), person1 = c(0.5, 
3), person2 = c(1.3, 5), person3 = c(1.7, 2)), 
class = "data.frame", row.names = c(NA, 
-2L))
  • Related