r - Pivot_longer 进入已存在的列

标签 r dplyr tidyr

我想将多个列两两地转变成一对已经存在的列

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/

相关文章:

r - 使用 R 中的条件对数据框中的特定组进行排序

R:通过将多个值与一个值进行比较来创建瀑布图

r - 如何在R中使用dplyr获取最近三个月的数据

r - 转换列表输出以在 dplyr 管道中创建 data.frame

database - R Shiny 的数据库管理

通过重采样调整向量大小

R - 按变量分组,然后分配唯一 ID

r - ggplot : how to plot heatmap regardless of the number of variables

r - 如何使用 dplyr 的 coalesce 函数和 group_by() 为每个人创建一行并填充所有值?

r - 如何使用gather()函数指定多列来整理数据