gsub用同一行代码替换和清理

我想知道是否可以替换一个字符并删除一行中的空格。

string = c("av13 personal care", "-11", "av13 personal care", "av14 personal services", 
    "av15 meals", "av29 visit friends", "av17 free time travel", 
 "av27 pubs", "av28 restaurants", "av28 restaurants", "av29 visit friends", 
 "av37 conversation", "av14 personal services", "av13 personal care", 
 "av13 personal care", "av13 personal care", "-11", "av13 personal care", 
 "av13 personal care", "av15 meals", "av6 cook, wash up", "av40 other leisure", 
 "av37 conversation", "av21 walking", "av40 other leisure", "av15 meals", 
 "av6 cook, wash up", "av13 personal care", "av21 walking", "av17 free time travel", 
 "av15 meals", "av35 read papers, magazines", "av27 pubs", "av13 personal     care", 
   "-11", "av13 personal care", "av2 paidwork at home", "av25 dances or    parties", 
"av1 paid work", "av1 paid work", "av1 paid work", "av1 paid work", 
"av2 paidwork at home", "av2 paidwork at home", "av13 personal care", 
 "av17 free time travel", "av29 visit friends", "av17 free time travel", 
 "av13 personal care", "-11", "av13 personal care")

而不是总是这样做

clean = gsub(pattern = "[A-z]", replacement = "", x = string)
clean = gsub(pattern = "[[:blank:]]", replacement = "", x = clean)

是否可以直接在第一行插入[[:blank:]]

我也有一个问题",""35," ),我怎么能摆脱它也在第一行?

小的更新我意识到,在我的(巨大的)数据集中,我还得到/之后gsub我的string - 你能帮我把它删除吗?


这是一个单行:

gsub(pattern = "[A-z ,/]", replacement = "", x = string) # added / to address the update

要么

gsub(pattern = "[A-z]| |,|/", replacement = "", x = string)

正如hwnd所指出的,范围[Az]实际上包含了Ascii代码中的AZ和az之间的几个特殊字符(相关的SO答案和ASCII表)。 这些特殊字符是: []^_`


角色类[Az]也会与其他角色匹配,我会使用:

gsub('[a-zA-Zt ,]', '', string)

注意: POSIX括号内的表达式[:blank:]与空格和制表符匹配。

如果只需要空间,那么:

gsub('[a-zA-Z, ]', '', string)
链接地址: http://www.djcxy.com/p/38317.html

上一篇: gsub replace and clean in same line of code

下一篇: as.numeric with comma decimal separators?