Go from long to wide using tidyr's pivot_wider

a 夏天 提交于 2021-02-20 04:26:28

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/64940108/go-from-long-to-wide-using-tidyrs-pivot-wider

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!