简体   繁体   中英

Go from long to wide using tidyr's pivot_wider

I have a simple long df where every element in the fi column should be a new column in the wide df. So the new df should have 10 columns A:J. The wide df should have two rows, "one" and "two".

Sounds like a job for pivot_wider, but I couldn't get it to work.

library("tidyverse")

df <- structure(list(fi = c("A", "B", "C", "D", "E", "F", "G", "H", 
                            "I", "J"), one = c(0.5, 1.4, 0.89, 1.4, 1.45, 1.25, 1.45, 1.4, 
                                               1.4, 1.5), two = c(0.75, 1.6, 1.05, 1.6, 1.45, 1.05, 1.65, 1.5, 
                                                                  1.55, 1.65)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
                                                                                                                   "data.frame"))
df

# Not it
df %>% 
  pivot_wider(names_from = fi, values_from = c(one, two))

Get data in long format first so that values of one and two are in same column and then cast it into wide format.

library(tidyr)

df %>%
  pivot_longer(cols = -fi) %>%
  pivot_wider(names_from = fi, values_from = value)

# name      A     B     C     D     E     F     G     H     I     J
#  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 one    0.5    1.4  0.89   1.4  1.45  1.25  1.45   1.4  1.4   1.5 
#2 two    0.75   1.6  1.05   1.6  1.45  1.05  1.65   1.5  1.55  1.65

With data.table :

library(data.table)
setDT(df)
dcast(melt(df, id.vars = 'fi'), variable ~fi, value.var = 'value')

We can use recast

library(reshape2)
recast(df, id.var = 'fi', variable ~ fi)

-output

#  variable    A   B    C   D    E    F    G   H    I    J
#1      one 0.50 1.4 0.89 1.4 1.45 1.25 1.45 1.4 1.40 1.50
#2      two 0.75 1.6 1.05 1.6 1.45 1.05 1.65 1.5 1.55 1.65

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