2017-01-07 37 views
3

在我的data.frame中,我有兩個帶文本的列(比如str1和str2)。我想添加一列表示str1中每一行str2的位置。在另一個字符串中查找data.frame中每一行的字符串位置(索引)

爲data.frame一個例子:

dt <- data.frame(str1 = c('ab/some words,cd/some words', 
'cd/some words,ab/some words', 'ab/some words,cd/some words', 'ef/some 
words,ab/some words'), str2 = c('ab', 'cd', 'cd', 'ef')) 

我要添加的列,指示STR2的在STR1每一行的位置。

這不起作用:

dt$str2.pos <- regexpr(dt$str2, dt$str1) 

我試圖得到一個輸出看起來像這樣:

      str1 str2 str2.pos 
1 ab/some words,cd/some words ab  1 
2 cd/some words,ab/some words cd  1 
3 ab/some words,cd/some words cd  15 
4 ef/some words,ab/some words ef  1 

回答

3

我們可以做

dt$str2.pos <- diag(sapply(dt$str2, function(x) regexpr(x, dt$str1))) 
dt$str2.pos 
#[1] 1 1 15 1 

如果我們正在爲相應的行執行此操作,請使用mapply/Map

mapply(regexpr, dt$str2, dt$str1) 
#[1] 1 1 15 1 
相關問題