2017-12-15 17 views
1

私は、データフレームの電車の中で二つの列があります:彼らはサーブも果たす配信
| | |キーワードRの同じデータフレーム内の別の列を持つ1つの列の単語の位置を見つけるにはどうすればよいですか?


ボックスが美しいです|
配達は時間に達しボックス

件名を果たす

件名のキーワードの位置を見つける方法は?

現在、私は、forループを使用しています:

for(k in 1:nrow(train)){ 
l <- unlist(gregexpr(train$keyword[k],train$subject[k],ignore.case = T)) 
train$position[k] <- l} 

は、他の方法はありますか?

+0

'のgrep(DF $キーワード、DFの$件名)データフレームの最後の行で' – abhiieor

+0

、 'L == C(6、17)'。 'train $ position [3]'を両方に設定しますか?その列にリストが保持されます。 –

+0

grep(df $ keyword、df $ Subject)これは一致します....私は、件名のキーワードの位置を見つけたいと思います。 – Prajna

答えて

0

ループは必要ない、ちょうどstringrまたはstringiパッケージ内で検索機能を使用しています。

train <- data.frame(subject = c("the box is beauty", "delivery reached on time", "they serve well"), 
        keyword = c("box", "delivery", "serve"), 
        stringsAsFactors = FALSE) 


library(stringr) 
train$position_stringr <- str_locate(train$subject, train$keyword)[,1] 
#locate returns a matrix and we are just interested in the start of keyword. 

library(stringi) 
train$position_stringi <- stri_locate_first(train$subject, regex = train$keyword)[,1] 
#locate returns a matrix and we are just interested in the start of keyword. 

train 
        subject keyword position_stringr position_stringi 
1  the box is beauty  box    5    5 
2 delivery reached on time delivery    1    1 
3   they serve well serve    6    6 
+0

ありがとうございました...それは動作します – Prajna

0

以下を使用できます。

#data.frame created using the below statements 
Subject <- c("the box is beauty","delivery reached on time","they serve well") 
Keyword <- c("box","delivery","serve") 
train <- data.frame(Subject,Keyword) 


#Solution 
library(stringr) 
for(k in 1:nrow(train)) 
{ 
    t1 <- as.character(train$Subject[k]) 
    t2 <- as.character(train$Keyword[k]) 
    locate_vector <- str_locate(t1,regex(t2,ignore.case=true))[[1]] 
    train$start_position[k] <- locate_vector 
    #If end position is also required, the second column from str_locate 
    #function could be used. 

}

+0

これは、私が書いたforループに似ています。他の方法では、件名にキーワードの位置を取得する必要があります。私はレコードがたくさんあり、forループには膨大な時間がかかります。 – Prajna