开发者

How to remove or insert substrings from an r variable without using system() and sed?

开发者 https://www.devze.com 2023-03-25 03:42 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号