Reputation: 463
I have 2 data frames and I would like to remove all columns in df1 that names match row names in df2.
df1
GO_267 GO_345 GO_5 GO_2
a 0 1 1 1
b 0 1 1 1
c 0 1 1 1
d 0 1 1 1
e 0 1 1 1
df2
z
GO_267 2
GO_345 3
GO_2 7
Upvotes: 2
Views: 227
Reputation: 887971
We can use select
library(dplyr)
df1 %>%
select(-row.names(df2))
df1 <- data.frame(GO_267=c(0,0,0,0,0), GO_345=c(1,1,1,1,1), GO_5=c(1,1,1,1,1),
GO_2=c(1,1,1,1,1))
df2 <- data.frame(z=c(2,3,7))
row.names(df2) <- c("GO_267", "GO_345", "GO_2")
Upvotes: 0
Reputation: 522762
You may using which
to subset, using the list of row names from the second data frame as the source of column names to exclude.
df1[ , -which(names(df1) %in% row.names(df2)), drop=FALSE]
GO_5
1 1
2 1
3 1
4 1
5 1
Data:
df1 <- data.frame(GO_267=c(0,0,0,0,0), GO_345=c(1,1,1,1,1), GO_5=c(1,1,1,1,1),
GO_2=c(1,1,1,1,1))
df2 <- data.frame(z=c(2,3,7))
row.names(df2) <- c("GO_267", "GO_345", "GO_2")
Upvotes: 3
Reputation: 389325
We could use setdiff
:
df1[setdiff(names(df1), rownames(df2))]
# GO_5
#a 1
#b 1
#c 1
#d 1
#e 1
Upvotes: 3