以下是我的数据示例:
dat<-read.table(text=" id bx1 Z1A Z1B Z1C QR1 bx2 Z2A Z2B Z2C QR2
1 1 1 2 3 C 18 2 2 1 E
2 11 2 3 3 B 14 3 3 3 A
",header=TRUE)
我想获得下表:
id bx Z QR Score
1 1 Z1A C 1
1 1 Z1B C 2
1 1 Z1C C 3
1 18 Z2A E 2
1 18 Z2B E 2
1 18 Z2C E 1
2 11 Z1A B 2
2 11 Z1B B 3
2 11 Z1C B 3
2 14 Z2A A 3
2 14 Z2B A 3
2 14 Z2C A 3
假设我有更多的bx和Z,并且已经完成了此操作,但是它不起作用。我想用tidyverse或其他包装。我找不到解决办法。
df1<-melt(dat, id.var= "id")
答案 0 :(得分:1)
在这种情况下,我们可以在分别执行<b>Text</b>
left_join
pivot_longer
或者另一种选择是做一个library(dplyr)
library(tidyr)
library(stringr)
dat %>%
select(id, starts_with('Z')) %>%
pivot_longer(cols = starts_with('Z'), values_to = 'Score',
names_to = 'Z') %>%
group_by(id) %>%
mutate(group = as.character(as.integer(factor(str_remove(Z, "[A-Z]$"))))) %>%
left_join(dat %>%
select(id, matches('^[^Z]')) %>%
pivot_longer(cols = -id, names_to = c(".value", "group"),
names_pattern = "^([A-Za-z]+)([0-9]+)")) %>%
select(-group)
# A tibble: 12 x 5
# Groups: id [2]
# id Z Score bx QR
# <int> <chr> <int> <int> <fct>
# 1 1 Z1A 1 1 C
# 2 1 Z1B 2 1 C
# 3 1 Z1C 3 1 C
# 4 1 Z2A 2 18 E
# 5 1 Z2B 2 18 E
# 6 1 Z2C 1 18 E
# 7 2 Z1A 2 11 B
# 8 2 Z1B 3 11 B
# 9 2 Z1C 3 11 B
#10 2 Z2A 3 14 A
#11 2 Z2B 3 14 A
#12 2 Z2C 3 14 A
,然后pivot_longer
选定的列
fill