简体   繁体   中英

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

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!

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM