R:在管道中合并几个gsub()函数 [英] R: combine several gsub() function in a pipe

查看:96
本文介绍了R:在管道中合并几个gsub()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要清除一些混乱的数据,我想开始使用管道%>%,但是如果gsub()不在管道的开头,则我的R代码无法正常工作,应该延迟很晚(注意:这个问题是不关心适当的导入,但与数据清理有关.

To clean some messy data I would like to start using pipes %>%, but I fail to get the R code working if gsub() is not at the beginning of the pipe, should occur late (Note: this question is not concerned with proper import, but with data cleaning).

简单的例子:

df <- cbind.data.frame(A= c("2.187,78 ", "5.491,28 ", "7.000,32 "), B = c("A","B","C"))

列A包含字符(在这种情况下为数字,但是也可以是字符串),需要清除. 步骤是

Column A contains characters (in this case numbers, but this also could be string) and need to be cleaned. The steps are

df$D <- gsub("\\.","",df$A)
df$D <- str_trim(df$D) 
df$D <- as.numeric(gsub(",", ".",df$D))

一个人可以轻松地通过管道

One easily could pipe this

df$D  <-  gsub("\\.","",df$A) %>%
          str_trim() %>%
          as.numeric(gsub(",", ".")) %>%

问题是第二个gsub,因为它要求输入....实际上是前一行的结果.

The problem is the second gsub because it asks for the Input .... which actually the result of the previous line.

请问,有谁能解释在管道的更深处如何使用gsub()之类的函数? 非常感谢!

Please, could anyone explain how to use functions like gsub() further down the pipeline? Thanks a lot!

系统:R 3.2.3,Windows

system: R 3.2.3, Windows

推荐答案

尝试一下:

library(stringr)

df$D <- df$A %>%
  { gsub("\\.","", .) } %>%
  str_trim() %>%
  { as.numeric(gsub(",", ".", .)) }

使用管道将数据作为 first 参数传递给下一个函数,因此,如果要在其他地方使用它,则需要将下一行包装在{}中并使用.作为数据标记".

With pipe your data are passed as a first argument to the next function, so if you want to use it somewhere else you need to wrap the next line in {} and use . as a data "marker".

这篇关于R:在管道中合并几个gsub()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆