Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

r - Matching information from different dataframes and filtering out redundant columns

In the first dataframe are site names that have been matched up with corresponding grid cells. These grid cells have unique column and row numbers. Here's an example of the first dataframe:

Site <- as.data.frame(c("Site.A","Site.B","Site.C"))
Row <- as.data.frame(c(1,2,3))
Column <- as.data.frame(c(5,4,3))
df1 <- cbind(Site,Row, Column)
colnames(df1) <- c("Site","Row","Column")

In a separate dataframe, I have separate information from all possible grid cells. An example:

eg1 <- rbind(c(1,2,3,4,5),c(5,4,3,2,1))
eg2 <- as.data.frame(matrix(sample(0:50, 15*10, replace=TRUE), ncol=5))
df2 <- rbind(eg1,eg2)
rownames(df2)[1:2] <- c("Row","Column")

What I would like to do is to filter columns in df2 so that they only have grid cells with columns and rows in df1. I would then need to match each site name with its corresponding grid cell. An example output of what I need.

Output <- df2[,1:3]
colnames(Output) <- c("Site.A","Site.B","Site.C")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One solution is as follows:

df2[, (df2['Row', ] %in% df1$Row) & (df2['Column', ] %in% df1$Column)]

Head of the output is as follows:

       V1 V2 V3
Row     1  2  3
Column  5  4  3
3      49 29 34
4      45 42 18
5       9 15 45
6      34 35 19

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...