R在DPLYR或DATA中重塑许多存根,TABLE [duplicate]

yhived7q  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(89)

这个问题已经有答案了

Reshape large dataset with multiple columns from wide to long(7个回答)
Reshaping multiple sets of measurement columns (wide format) into single columns (long format)(8个回答)
Data frame from wide to long with multiple variables and ids R [duplicate](4个回答)
Wide to Long format with multiple variables? [duplicate](1个回答)
17天前关闭
这是我的数据

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')


没有成功

k97glaaz

k97glaaz1#

您可以使用tidyr::pivot_longer尝试以下操作。将names_to中的第二个参数设置为NA将删除不需要的列:

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)

相关问题