R 从长格式到宽格式重塑数据框? [英] R Reshape data frame from long to wide format?

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

问题描述

将下面的数据框从长格式转换为宽格式的最佳方法是什么?我尝试使用 reshape 但没有得到想要的结果.

What's the best way to convert the data frame below from long to wide format? I tried to use reshape but didn't get the desired results.

2015    PROD A  test1
2015    PROD A  blue
2015    PROD A  50
2015    PROD A  66
2015    PROD A  66
2018    PROD B  test2
2018    PROD B  yellow
2018    PROD B  70
2018    PROD B  88.8
2018    PROD B  88.8
2018    PROD A  test3
2018    PROD A  red
2018    PROD A  55
2018    PROD A  88
2018    PROD A  90

推荐答案

一个可能的解决方案是这样的

A possible solution is this

library(tidyverse)

df = read.table(text = "
                year prod value
                2015    PRODA  test1
                2015    PRODA  blue
                2015    PRODA  50
                2015    PRODA  66
                2015    PRODA  66
                2018    PRODB  test2
                2018    PRODB  yellow
                2018    PRODB  70
                2018    PRODB  88.8
                2018    PRODB  88.8
                2018    PRODA  test3
                2018    PRODA  red
                2018    PRODA  55
                2018    PRODA  88
                2018    PRODA  90
                ", header=T, stringsAsFactors=F)

df %>%
  group_by(year, prod) %>%                           # for each year and prod combination
  mutate(id = paste0("new_col_", row_number())) %>%  # enumerate rows (this will be used as column names in the reshaped version)
  ungroup() %>%                                      # forget the grouping
  spread(id, value)                                  # reshape

# # A tibble: 3 x 7
#    year prod  new_col_1 new_col_2 new_col_3 new_col_4 new_col_5
#   <int> <chr> <chr>     <chr>     <chr>     <chr>     <chr>    
# 1  2015 PRODA test1     blue      50        66        66       
# 2  2018 PRODA test3     red       55        88        90       
# 3  2018 PRODB test2     yellow    70        88.8      88.8 

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

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