简体   繁体   English

R跨多个值列

[英]R spread across multiple value columns

My dataset looks like this - 我的数据集看起来像这样-

dataset = data.frame(Site=c(rep('A',6),rep('B',6)),Date=c(rep(c('2019-05-31','2019-04-30','2019-03-31'),4)),Question=c(rep('Q1',3),rep('Q2',3)),Score=runif(12,0.5,1),Average=runif(12,0.5,1))

I'd like to spread columns in such a way that the the first two columns contain the Site and Question and the remaining columns are have the Score_Date and Average_Date 我想以这样的方式spread列,使得前两列包含“ Site和“ Question ,其余列具有“ Score_Date”和“ Average_Date”

Here's an example of what the first line of the resulting table would look like 这是结果表第一行的示例

  Site Question Score_2019.03.31 Score_2019.04.30 Score_2019.05.31 Average_2019.03.31 Average_2019.04.30 Average_2019.05.31
   A       Q1        0.9117566        0.8661078        0.5624139          0.7246694          0.8870703          0.6401099

I tried using unite & spread from tidyr but nowhere close to the result 我试着从tidyr使用unitespread ,但距离结果tidyr

Any inputs would be highly appreciated 任何输入将不胜感激

Using tidyr and dplyr from the tidyverse, you could do the following: 使用tidyverse中的tidyr和dplyr,您可以执行以下操作:

library(tidyverse)
dataset %>% 
  nest(Score, Average, .key = 'value_col') %>% 
  spread(key = Date, value = value_col) %>% 
  unnest(`2019-03-31`, `2019-04-30`, `2019-05-31`, .sep = "_")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM