我有一个问题困扰了我很长一段时间:我应该如何删除以问号开头的模式?
例如:
## dataframe named test
x y
1 gffsd?lang=dfs
2 sdldfsd?lang=gsd
3 eoriwesd?lang=fh
4 eriywo?lang=asd
Run Code Online (Sandbox Code Playgroud)
我想要的是:
x y
1 gffsd
2 sdldfsd
3 eoriwesd
4 eriywo
Run Code Online (Sandbox Code Playgroud)
我尝试了几种方法,包括:
test$y = sapply(strsplit(test$y, '?'), head, 1)
test$y = sapply(strsplit(test$y, '?lang='), head, 1)
gsub("?",NA, test$y, fixed = TRUE)
Run Code Online (Sandbox Code Playgroud)
不幸的是,他们都失败了.
提前致谢!
BTW,任何人都知道如何将"®"替换为" - "
gsub 可以使用正确的正则表达式.
test$y = gsub("\\?.*", "", test$y)
test
x y
1 1 gffsd
2 2 sdldfsd
3 3 eoriwesd
4 4 eriywo
Run Code Online (Sandbox Code Playgroud)
你需要逃避问号"\\?" 并且".*"表示您要删除问号后的所有内容.
你的第二个问题也是gsub如此.
string = 'anybody knows how to replace ® to -'
gsub("®", "-", string)
[1] "anybody knows how to replace - to -"
Run Code Online (Sandbox Code Playgroud)