So I have a .txt file with several dataframes. It looks similar to the following example:
$stim
rt 82289.8878539, 82294.8309221, 82299.3357436, 82304.1822179
category 1, 2, 1, 1
orient 263, 313, 266, 253
$stim
rt 82289.887000, 82294.8309333, 82299.3357444, 82304.1822179
category 1, 2, 2, 2
orient 263, 310, 360, 250
Each dataframe in this .txt file corresponds to a filename, which I have stored in a list. What I would like to do is replace the $stim with a filename. I have constructed a for loop to do this, which looks like this:
library(stringr)
text <- readLines("filepath")
wrong_words <- ("$stim")
new_words <- (filenames)
for (i in seq_along(wrong_words)) {
text <- str_replace_all(text, wrong_words[i], new_words[i])
}
text
writeLines(text, con="filepath")
However, when I run this loop, nothing changes and I get the exact same .txt file as before. What am I doing wrong?
What you want is
grephere and loop over the matches.stringi::stri_replace_all_regexor the like rather replace by dictionary, i.e. all "$stim" would be replaced with the same new word. We can wrap this in a function and nevertheless include a dictionary feature. To avoid feature creep, we leave out thereadLines/writeLines.Usage
You can also provide a dictionary.
Complete approach