Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

dataframe - R Reshape data frame from long to wide format?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...