How to remove or insert substrings from an r variable without using system() and sed?
I want to be able to remove or insert arbitrary substrings from an existi开发者_如何学Gong r variable. My current solution uses system()
, but I'm sure there's an easier and more elegant way:
> filename <- "remove_this_my_file.txt"
> (file <- system(paste("echo ", filename, "| sed 's/remove_this_\\(.*\\)/\\1/'",sep=""), intern=T))
[1] "my_file.txt"
By the way, substr()
is no good, since the position of the substring might vary from filename to filename.
You can use regular expressions in R via the grep
, sub
, regexpr
, and similar commands. It sounds like you'd want sub
or gsub
. These operations are vectorized, which comes in handy at times.
> filename <- sub("remove_this_","",filename)
> filename
[1] "my_file.txt"
If you're used to Perl-style regular expressions, you'll want to set the ,perl=TRUE
option.
精彩评论