【问题标题】:Extract from 2nd column based on string content in 1st column根据第一列中的字符串内容从第二列中提取
【发布时间】:2017-05-25 20:05:54
【问题描述】:

请帮忙,我需要从 B 列中提取所有条目 它出现在数据框中的 A 列中

我需要根据具有 GK104 的字符串搜索 A 列 也就是说,如果A列的enries中有GK104,它将从B列获取相应的条目

A                    B
DT-GK104-BIN1-E-A1  8000_AMKR
DT-GK104-BIN2-E-A2  8000_ASET
DT-GK104-BIN3-E-A1  8000_CPAC
DT-GK104-BIN4-E-ZK  8000_PWOO
DT-GK104-BIN5-E-ZK  8000_SPIL

【问题讨论】:

  • grep("GK104",df$A) 将给出 A 列包含 GK104 的行号向量。然后,您可以使用它来引用 B 列。

标签: r


【解决方案1】:

这很简单。要继续 Andrew Gustar 的评论,您只需使用grepl

df <- 
"A                    B
DT-GK104-BIN1-E-A1  8000_AMKR
DT-GK104-BIN2-E-A2  8000_ASET
DT-GK104-BIN3-E-A1  8000_CPAC
DT-GK104-BIN4-E-ZK  8000_PWOO
DT-GK104-BIN5-E-ZK  8000_SPIL"

df <- read.table(text=df, header = T, stringsAsFactors = F)

# Save a value which you want to match
value <- "A1"

# You can get a filtered dataframe
df[grepl(value, df$A),]
                   A         B
1 DT-GK104-BIN1-E-A1 8000_AMKR
3 DT-GK104-BIN3-E-A1 8000_CPAC

# Or you can just get a character vector of matched values in the second column 
df$B[grepl(value, df$A)]
[1] "8000_AMKR" "8000_CPAC"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2014-07-30
    • 1970-01-01
    • 2018-03-13
    • 2020-04-04
    • 2020-06-30
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多