首页 > 解决方案 > 如何提取数据框中定义的列集之间的共享事件?

问题描述

我正在尝试在定义的列集之间进行特定比较,以使两列的行因子都具有非零值。然后我想将感兴趣的数据提取到一个新的数据框中。我有有效的代码,但我想帮助将其简化为一个 for 循环,其中给出了定义的对比(A&C、B&C、D&F、E&F、G&H)。

这是我在 R 中使用 dplyr 的代码。

# make an example dataframe
a<-sample(0:10, 100, replace=TRUE)
b<-sample(0:10, 100, replace=TRUE)
c<-sample(0:10, 100, replace=TRUE)
d<-sample(0:10, 100, replace=TRUE)
e<-sample(0:10, 100, replace=TRUE)
f<-sample(0:10, 100, replace=TRUE)
g<-sample(0:10, 100, replace=TRUE)
h<-sample(0:10, 100, replace=TRUE)

x <- data.frame("A" = a, "B"=b , "C"=c, "D"=d, "E" = e, "F"=f , "G"=g, "H"=h, "ID" = seq(1000,1099))

# use dplyr to compare and pull out data of interest
AC<- x %>% 
   select(ID,`A`,`C`) %>%
   filter(`A` > 0 , `C` > 0)%>%
   select(-c(`C`))

BC<- x %>% 
  select(ID,`B`,`C`) %>%
  filter(`B` > 0 , `C` > 0) %>%
  select(-c(`C`))


DF<- x %>% 
  select(ID,`D`,`F`) %>%
  filter(`D` > 0 , `F` > 0) %>%
  select(-c(`F`))

EF<- x %>% 
  select(ID,`E`,`F`) %>%
  filter(`E` > 0 , `F` > 0)%>%
  select(-c(`F`))

GH<- x %>% 
  select(ID,`G`,`H`) %>%
  filter(`G` > 0 , `H` > 0)%>%
  select(-c(`H`))

# use dplyr to combine
new_x<-full_join(AC,BC, by='ID')
new_x<-full_join(new_x,DF, by='ID')
new_x<-full_join(new_x,EF, by='ID')
new_x<-full_join(new_x,GH, by='ID')

标签: rdplyr

解决方案


我们可以使用reducefrompurrr包来简化最后一部分。我们还可以设计一个函数来简化代码。

library(tidyverse)

# Create two vecotrs showing the variables you are interested in
interest1 <- c("A", "B", "D", "E", "G")
interest2 <- c("C", "C", "F", "F", "H")

# Design a function to do the compare
compare <- function(int1, int2, dat){
  dat2 <- dat %>% 
    select(ID, int1, int2) %>%
    filter(!!sym(int1) > 0 , !!sym(int2) > 0)%>%
    select(-int2)
  return(dat2)
}

# Loop through interest1 and interest2
new_x <- map2(interest1, interest2, compare, dat = x) %>%
  reduce(full_join, by = "ID")

推荐阅读