简体   繁体   English

R中的管道修剪和gsub

[英]Piping trimws and gsub in R

I am able to trim out white space and punctuation in R using the below nested functions: 我可以使用以下嵌套函数在R中修剪空白和标点符号:

x <- "    a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=    "

y <- trimws(gsub("[[:punct:]]", "", x)) #returns "a1" as desired

But I'd like to make use of the magrittr / dplyr piping operator (%>%) instead of nesting functions because it makes the code more readable for others, but can't seem to make it work. 但是我想使用magrittr / dplyr管道运算符(%>%)而不是嵌套函数,因为它使代码对其他用户更具可读性,但似乎无法使其正常工作。 Here's what I'm trying: 这是我正在尝试的:

x <- "    a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=    "

z <- gsub("[[:punct:]]", "", x) %>% trimws(x)

Here's the error I'm receiving: 这是我收到的错误:

Error in match.arg(which) : 'arg' should be one of “both”, “left”, “right” match.arg(which)中的错误:“ arg”应为“ both”,“ left”,“ right”之一

This error doesn't make sense to me because leaving out additional arguments to trimws normally removes left and right trailing spaces, so I shouldn't have to specify "both". 这个错误对我来说没有任何意义,因为在triws中遗漏其他参数通常会删除左尾和右尾空格,因此我不必指定“ both”。 This error is only thrown when used in conjunction with gsub in the piping syntax. 仅当在管道语法中与gsub结合使用时,才会引发此错误。

What am I missing about how piping works? 我对管道的工作方式缺少什么? I've reviewed magrittr to no avail. 我没有评论magrittr。

Try this: 尝试这个:

library(magrittr)
x <- "    a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=    "   # input

x %>% 
  gsub(pattern = "[[:punct:]]", replacement = "") %>%
  trimws -> z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM