I have a datset consisting of sentences with consecutive word repeats:
DATA:
df <- data.frame(
Turn = c("oh is that that steak i got the other night", # that that
"no no no i 'm dave and you 're alan", # no no no
"yeah i mean the the film was quite long though", # the the
"it had steve martin in it it 's a comedy")) # it it
OBJECTIVE:
What I'd like to obtain are three more columns added to this dataframe:
df$rep_Word: a column specifying the word that gets repeateddf$rep_Pos: a column specifying the first position in the sentence at which the word is repeateddf$rep_Numb: a column specifying the number of times the word gets repeated
So the expected dataframe looks like this:
EXPECTED RESULT:
df
Turn rep_Word rep_Pos rep_Numb
1 oh is that that steak i got the other night that 4 1
2 no no no i 'm dave and you 're alan no 2 2
3 yeah i mean the the film was quite long though the 5 1
4 it had steve martin in it it 's a comedy it 7 1
ATTEMPTED SOLUTION SO FAR:
My hunch is that the sought information on repeated word, and position and number of repeats can be approached with strsplit and the function duplicated, e.g., thus:
df_split <- apply(df, 2, function(x) strsplit(x, "\\s"))
df_split
$Turn
$Turn[[1]]
[1] "oh" "is" "that" "that" "steak" "i" "got" "the" "other" "night"
$Turn[[2]]
[1] "no" "no" "no" "i" "'m" "dave" "and" "you" "'re" "alan"
$Turn[[3]]
[1] "yeah" "i" "mean" "the" "the" "film" "was" "quite" "long" "though"
$Turn[[4]]
[1] "it" "had" "steve" "martin" "in" "it" "it" "'s" "a" "comedy"
For example, for the first sentence in df, duplicatedshows which word gets repeated (namely the one for which duplicated evaluates to TRUE) and both number and position of the repeat could also be read-off that information:
duplicated(df_split$Turn[[1]])
[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
The problem is that I don't know how to operationalize duplicatedin such a way as to obtain the desired added columns in df. Help with that endeavor is much appreciated.