【问题标题】:Subset of df based on matches of another df (R/ R Studio)基于另一个 df 匹配的 df 子集(R/R Studio)
【发布时间】:2022-01-24 08:45:29
【问题描述】:

我有我的原始数据框,我只想从中保留某些行。

head(original_df)
  id    roi            mean  sd
1 1102A HarvardOxford 0.4675 0.1345
2 1102A HarvardOxford 0.4456 0.1345
3 1102A HarvardOxford 0.4567 0.788
4 1102A HarvardOxford 0.1231 0.8976
5 1102A Lh_func_3     0.1231 0.8678
6 1102A Lh_func_      0.2342 0.67856

id 列包括主题代码 + 一个“A”或“B”或“C”,具体取决于会话。 我有另一个 df (subs),只有一个变量,其中包括我想保留的 ids(它包含来自原始 df 的所有 id 的选择)。在这个数据框中只有主题代码,没有会话指示器。

head(subs)
         V1
1 1102
2 1103
3 1104
4 1107
5 1110
6 1111

如何只保留原始数据框中与 subs$V1 列匹配的行?

【问题讨论】:

    标签: r match subset


    【解决方案1】:

    使用substr。

    subset(df1, substr(id, 1, 4) %in% df2$V1)
    #      id          x
    # 2 1103A  0.2051387
    # 4 1103B -0.8920853
    # 6 1103C  0.8064977
    

    数据:

    df1 <- structure(list(id = c("1102A", "1103A", "1102B", "1103B", "1102C", 
    "1103C"), x = c(-0.946458205218808, 0.205138719393085, -0.734810811183742, 
    -0.892085335997171, 0.327500189913222, 0.806497715247655)), class = "data.frame", row.names = c(NA, 
    -6L))
    
    df2 <- structure(list(V1 = 1103:1105), class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

      【解决方案2】:

      我将首先在您的原始 data.frame 中创建另一列,仅提取 ID 中的数字。

      library(tidyverse)
      original.df2 <- mutate(original.df, V1 = substr(id,1,4) ## select only first 4 digits
      

      然后您可以根据文件subs过滤行。

      filter(original.df2, V1 %in% subs$V1)
      

      应该可以的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        • 2012-10-12
        相关资源
        最近更新 更多