尝试一次创建4列数据

时间:2018-04-17 04:48:18

标签: r dplyr spread

我正在努力使我的数据比现在更广泛。我尝试使用spread,但我想一次传播4个变量。样本数据集是:

  df <- data.frame(Year <- c("2017","2018"),
                           ID <- c(1,1),
                           Score <- c("21","32"),
                           Score2 <- c("24","20"),
                           Score3 <- c("33", "26"),
                           Score4 <- c("25","32"))

     Year ID Score Score2 Score3 Score4
   1 2017  1    21     24     33     25
   2 2018  1    32     20     26     32

我想把它扩大,以便这两年的所有分数都是这样的一行:

  Year Score Score2 Score3 Score4 Year2 Score18 Score218 Score318 Score418
1 2017    21     24     33     25  2018      32       20       26       32

&#34; Year2&#34;专栏并非完全必要,但我想在2017年到2018年之间进行一些解读。

任何帮助或指导将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:2)

我们可以使用dcast

中的data.table
library(data.table)
dcast(setDT(df), ID ~ rowid(ID), value.var = setdiff(names(df), 'ID'), 
          sep="")[, ID :=  NULL][]
#  Year1 Year2 Score1 Score2 Score21 Score22 Score31 Score32 Score41 Score42
#1:  2017  2018     21     32      24      20      33      26      25      32

reshape

中的base R
reshape(transform(df, tvar = seq_len(nrow(df))), 
        idvar = 'ID', direction = 'wide', timevar = 'tvar')[-1]
#   Year.1 Score.1 Score2.1 Score3.1 Score4.1 Year.2 Score.2 Score2.2 Score3.2 Score4.2
#1   2017      21       24       33       25   2018      32       20       26       32

数据

df <- data.frame(Year = c(2017, 2018),
                           ID = c(1,1),
                           Score = c(21,32),
                           Score2 = c(24,20),
                           Score3 =  c(33, 26),
                           Score4= c(25, 32))

答案 1 :(得分:1)

另一种方法可能是

library(tidyverse)
library(splitstackshape)

df %>%
  group_by(ID) %>%
  summarise_all(funs(toString)) %>%
  cSplit(names(.)[-1], ",")

输出为:

   ID Year_1 Year_2 Score_1 Score_2 Score2_1 Score2_2 Score3_1 Score3_2 Score4_1 Score4_2
1:  1   2017   2018      21      32       24       20       33       26       25       32

示例数据:

df <- data.frame(Year = c("2017","2018"),
                 ID = c(1,1),
                 Score = c("21","32"),
                 Score2 = c("24","20"),
                 Score3 = c("33", "26"),
                 Score4 = c("25","32"))