如何使用 dplyr stringr 删除列中每一行括号内的所有内容 [英] How to remove everything within brackets for every row in a column using dplyr stringr

查看:31
本文介绍了如何使用 dplyr stringr 删除列中每一行括号内的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:


library(tidyverse)数据 <- tribble(~x, ~y,1, "富",2、《酒吧(103 xxx)》、3、酒吧"、4、《富(yyy)》)数据#># 小费:4 x 2#>xy#><dbl><chr>#>1 1 富#>2 2 巴 (103 xxx)#>3 3 巴#>4 4 foo (yyy)

我想要做的是通过删除 () 括号中包含的所有字符串来清理 y 列.结果:

 x y<dbl><chr>1 1 富2 2 巴3 3 巴4 4 英尺

我该怎么做?

我试过这个错误:

>dat %>% stringr::str_replace(y, "\\([a-zA-Z0-9]+\\)","")stringr::str_replace(., y, "\\([a-zA-Z0-9]+\\)", "") 中的错误:未使用的参数 ("")

解决方案

问题是管道%>%,将dat传递给str_replace 作为第一个参数,即错误消息中的 dot,这不是 str_replace 所期望的:

<块引用>

<代码>>stringr::str_replace(., y, "\\([a-zA-Z0-9]+\\)", "") 中的错误:# ^ 数据经过这里

您可以使用 str_replacemutate 来创建新列:

dat %>% mutate(y = trimws(str_replace(y, "\\(.*?\\)", "")))# 小费:4 x 2# x y# <dbl><chr>#1 1 foo#2 2 条#3 3 条#4 4 foo

<小时>

如果你想在pipe之后直接应用str_replace,你只能修改一个列/向量:

#这里使用pull提取列并对其进行操作dat %>% pull(y) %>% str_replace("\\(.*?\\)", "") %>%trimws()# [1] "foo" "bar" "bar" "foo"

I have the following data frame:


library(tidyverse)
dat <- tribble(
  ~x, ~y,
  1,  "foo",
  2,  "bar (103 xxx)",
  3,  "bar",
  4,  "foo (yyy)"
)

dat 
#> # A tibble: 4 x 2
#>       x             y
#>   <dbl>         <chr>
#> 1     1           foo
#> 2     2 bar (103 xxx)
#> 3     3           bar
#> 4     4     foo (yyy)

What I want to do is to clean column y by removing all strings that is contained in () bracket. Resulting in:

      x             y
  <dbl>         <chr>
1     1           foo
2     2           bar 
3     3           bar
4     4           foo

How can I do it?

I tried this with error:

> dat  %>% stringr::str_replace(y, "\\([a-zA-Z0-9]+\\)","")
Error in stringr::str_replace(., y, "\\([a-zA-Z0-9]+\\)", "") : 
  unused argument ("")

解决方案

The problem is the pipe %>%, which passes dat to str_replace as first argument, i.e. the dot in the error message, which is not what str_replace is expecting:

> Error in stringr::str_replace(., y, "\\([a-zA-Z0-9]+\\)", "") :
 #                              ^   dat passed here

You can use str_replace with mutate to create a new column:

dat %>% mutate(y = trimws(str_replace(y, "\\(.*?\\)", "")))

# A tibble: 4 x 2
#      x     y
#  <dbl> <chr>
#1     1   foo
#2     2   bar
#3     3   bar
#4     4   foo


If you want to apply str_replace directly after the pipe, you can only modify a column/vector:

# here use pull to extract the column and manipulate it
dat %>% pull(y) %>% str_replace("\\(.*?\\)", "") %>% trimws()
# [1] "foo" "bar" "bar" "foo"

这篇关于如何使用 dplyr stringr 删除列中每一行括号内的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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