我想将多个列两两地转变成一对已经存在的列
have <- tribble(
~egtest,~egorres, ~egorresu, ~hrorres,~hrorresu,~prorres,~prorresu,~uninteresing,
"qt", 500,"msec",90,"bpm",100,"msec", "cat",
"qtc", 370,"msec",NA,"bpm",103,"msec","dog",
"pra",83,"msec",79,"bpm",97,"msec","cat"
)
对此:
want <- tribble(
~egtest,~egorres, ~egorresu,~uninteresting,
"qt", 500,"msec","cat",
"qtc", 370,"msec","dog",
"pra",83,"msec","cat",
"hr",90,"bpm","cat",
"pr",100,"msec","cat",
"hr",NA,"bpm","dog",
"pr",103,"msec","dog",
"hr",79,"bpm","cat",
"pr",97,"msec","dog"
)
现在我的代码是
colstopivotEG <- function(table){
out <- subset(colnames(table),grepl(pattern = "orres\\b",colnames(table)))
out <- out[out != "egorres"]
#print(out)
return(out)
}
pivot_eg <- function(ndf){
EG1 <- pivot_longer(ndf,
cols = colstopivotEG(ndf),
names_pattern = "(.*)orres",
names_to="egtest",
values_to="egorres")
EG2 <- pivot_longer(ndf,
cols=ends_with("orresu"),
names_pattern = "(.*)orresu",
values_to="egorresu")
ndf <- bind_cols(EG1,EG2 %>% select(EGORRESU_STD))
}
但我似乎无法转向现有的专栏,我没有想法,任何帮助都会非常感谢!
PS:有很多列不想旋转
最佳答案
我会将 tibble 按列分成两部分:
- 以
eg
开头的列(保持原样) - 其余的(旋转它们)。
之后(修复第二个小标题的名称后)我们可以再次将两个小标题绑定(bind)在一起。
library(dplyr)
library(tidyr)
eg <- have %>%
select(starts_with("eg"))
rest <- have %>%
select(-starts_with("eg")) %>%
pivot_longer(everything(),
names_pattern = "(hr|pr)(.+)",
names_to = c("egtest", ".value")) %>%
rename(egorres = orres,
egorresu = orresu)
bind_rows(eg, rest)
这给出了
egtest egorres egorresu
<chr> <dbl> <chr>
1 qt 500 msec
2 qtc 370 msec
3 pra 83 msec
4 hr 90 bpm
5 pr 100 msec
6 hr NA bpm
7 pr 103 msec
8 hr 79 bpm
9 pr 97 msec
关于r - Pivot_longer 进入已存在的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71753108/