【问题标题】:Matching information from different dataframes and filtering out redundant columns匹配来自不同数据帧的信息并过滤掉冗余列
【发布时间】:2016-05-13 16:13:56
【问题描述】:

在第一个数据框中是与相应网格单元匹配的站点名称。这些网格单元具有唯一的列号和行号。这是第一个数据框的示例:

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")

在一个单独的数据框中,我有来自所有可能的网格单元的单独信息。一个例子:

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")

我想做的是过滤 df2 中的列,以便它们只有在 df1 中具有列和行的网格单元格。然后,我需要将每个站点名称与其对应的网格单元格匹配。我需要的示例输出。

Output <- df2[,1:3]
colnames(Output) <- c("Site.A","Site.B","Site.C")

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    一种解决方法如下:

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

    头部输出如下:

           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
    

    【讨论】:

    • 非常感谢。然后我如何匹配站点名称?是否总是以相同的顺序完成,以便我可以更改列名?
    • 姓名:names(output) &lt;- df1$Site[mapply(function(r, c){which(r == df1$Row &amp; c == df1$Column)}, output[1,], output[2,])]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 2021-03-21
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多