根据第1列中的字符串内容从第2列中提取

时间:2017-05-25 10:11:13

标签: r

请帮助,我需要从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

1 个答案:

答案 0 :(得分:0)

这很简单。要继续发表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"