r - 如何提取数据框中定义的列集之间的共享事件?
问题描述
我正在尝试在定义的列集之间进行特定比较,以使两列的行因子都具有非零值。然后我想将感兴趣的数据提取到一个新的数据框中。我有有效的代码,但我想帮助将其简化为一个 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')
解决方案
我们可以使用reduce
frompurrr
包来简化最后一部分。我们还可以设计一个函数来简化代码。
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")
推荐阅读
- android - 谷歌移动视觉二维码阅读器从损坏的二维码中读取可能的原始数据
- python - 如何转置数据框中的特定列并获取 Pandas 中其他列的计数
- javascript - hashSync 需要的数据和盐
- mysql - 在 sqoop 导出中,对于长文本,Sqoop 将列设为空
- cookies - 以编程方式清除 Cookie 在 Postman 和 Newman 中不起作用
- python-3.x - 预期的 str、bytes 或 os.PathLike 对象,而不是 _io.TextIOWrapper
- javascript - 反应单选按钮在第一次点击时不起作用
- parameters - 手册中的“zsh 数组参数”我无法完全理解。任何人都可以通过举例来解释这一点吗?
- python - 如何使用 Google Colab 从 Github 存储库运行 .py 文件?
- c# - 如何将身份验证添加到 web api