使用 tidyr 的 pivot_wider 从长到宽 [英] Go from long to wide using tidyr's pivot_wider

查看:30
本文介绍了使用 tidyr 的 pivot_wider 从长到宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的长 df,其中 fi 列中的每个元素都应该是宽 df 中的一个新列.所以新的 df 应该有 10 列 A:J.宽 df 应该有两行,一"和两个".

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".

听起来像pivot_wider的工作,但我无法让它发挥作用.

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

推荐答案

先获取长格式数据,使 onetwo 的值在同一列,然后将其转换为宽幅.

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

使用 data.table :

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

这篇关于使用 tidyr 的 pivot_wider 从长到宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆