使用 tidyR 从长到宽的数据? [英] Long to wide data with tidyR?

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

问题描述

我有类似这样的数据

df = data.frame(name=c("A","A","B","B"),
                group=c("g1","g2","g1","g2"),
                V1=c(10,40,20,30),
                V2=c(6,3,1,7))

我想把它改成这样:

df = data.frame(name=c("A", "B"),               
                V1.g1=c(10,20),
                V1.g2=c(40,30),
                V2.g1=c(6,1),
                V2.g2=c(3,7))

用 tidyR 可以做到吗?

Is it possible to do it with tidyR?

我可以通过重塑来做到这一点

I can do it with reshape

reshape(df, idvar='name', timevar='group', direction='wide')

但是学习新东西总是好的.

but is always good to learn something new.

推荐答案

tidyr 1.0.0 起,您可以执行以下操作:

Since tidyr 1.0.0 you can do the following:

library(tidyr)

df = data.frame(name=c("A","A","B","B"),
                group=c("g1","g2","g1","g2"),
                V1=c(10,40,20,30),
                V2=c(6,3,1,7))

pivot_wider(df, names_from = "group", values_from = c("V1", "V2"), names_sep = ".")
#> # A tibble: 2 x 5
#>   name  V1.g1 V1.g2 V2.g1 V2.g2
#>   <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 A        10    40     6     3
#> 2 B        20    30     1     7

reprex 包 (v0.3.0) 于 2019 年 9 月 14 日创建

Created on 2019-09-14 by the reprex package (v0.3.0)

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

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