2017-05-25 79 views
1

請幫助字符串內容,我需要提取從B列 這似乎對那些在A列從數據幀中的所有條目提取基於第1列

我需要列一個基於搜索其具有GK104 也就是說,如果列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 
+3

'grep的( 「GK104」,DF $ A)'會給在A列中包含'GK104'行數的向量。然後您可以使用它來引用列B. –

回答

0

對應條目這是簡單的。要繼續安德魯·古斯塔夫的評論,你只需要使用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"