R 重塑 DPLYR 或 DATA.TABLE 中的许多存根

问题描述 投票:0回答:1

这是我的数据

STUDENT CLASS   TIME_1  TIME_2  math1   math2   hist1   hist2
1   90  119 106 4   6   3   10
2   8       115 4   7       2
3   3   74  112 5   7   8   10

我希望使这个文件从宽到长

STUDENT CLASS   TIME    math    hist
1   90  119 4   3
1   90  106 6   10
2   8       4   2
2   8   115 7   
3   3   74  5   8
3   3   112 7   10

我试过了,

melt(setDT(DATA), measure = patterns("TIME_", "math", "hist"), variable.name = 'var', value.name = c('TIME_', 'math', 'hist') 

没有成功

r dplyr data.table
1个回答
2
投票

您可以使用

tidyr::pivot_longer
尝试以下操作:

df %>%
  pivot_longer(cols = -c(STUDENT, CLASS), 
               names_to = c(".value", NA), 
               names_pattern = "(\\D+)(\\d+)")

输出

  STUDENT CLASS TIME_  math  hist
    <int> <int> <int> <int> <int>
1       1    90   119     4     3
2       1    90   106     6    10
3       2     8    NA     4    NA
4       2     8   115     7     2
5       3     3    74     5     8
6       3     3   112     7    10

数据

df <- read.table(text = "STUDENT CLASS   TIME_1  TIME_2  math1   math2   hist1   hist2
1   90  119 106 4   6   3   10
2   8   NA    115 4   7   NA    2
3   3   74  112 5   7   8   10", h = TRUE)

df_want <- read.table(text = "STUDENT CLASS   TIME    math    hist
1   90  119 4   3
1   90  106 6   10
2   8     NA  4   2
2   8   115 7   NA
3   3   74  5   8
3   3   112 7   10", h = TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.