用Gsub替换不完整的支架[重复]

时间:2022-04-16 04:39:50

This question already has an answer here:

这个问题在这里已有答案:

I want to do a simple replace in R for the following column:

我想在R中为以下列做一个简单的替换:

df

                                                                        Songs
1                                                      Saga (Skit) [feat. RZA
2                                                                     Revenge
3                                                           Whatever You Want
4                                                               What About Us
5                                                              But We Lost It
6                                                                     Barbies

I want to do two different replacements:

我想做两种不同的替代品:

1) Replace "[" with blank

1)将“[”替换为空白

2) Replace "]" with blank

2)用空白替换“]”

Need to do this separately though because some of my values only has 1 on the brackets like the first value in the Songs column.

需要单独执行此操作,因为我的某些值在括号中只有1,如Songs列中的第一个值。

df[,1]<-gsub("[","",df[,1])

Error:

Error in gsub("[", "", newdf2[, 1]) : 
  invalid regular expression '[', reason 'Missing ']''

How do I go about going around this invalid regular expression error?

如何解决这个无效的正则表达式错误?

Thanks!

2 个解决方案

#1


2  

Sometimes you have to double escape things in R. This should work to do both the replacements in one go.

有时你必须在R中双重逃避。这应该可以同时完成两个替换。

gsub("\\[|\\]", "", df$Songs)

#2


2  

The [ is a metacharacter, so it needs to be escaped

[是一个元字符,因此需要进行转义

gsub("\\[|\\]", "", df$Songs)

Or other way is

或者其他方式

gsub("[][]", "", df$Songs)

#1


2  

Sometimes you have to double escape things in R. This should work to do both the replacements in one go.

有时你必须在R中双重逃避。这应该可以同时完成两个替换。

gsub("\\[|\\]", "", df$Songs)

#2


2  

The [ is a metacharacter, so it needs to be escaped

[是一个元字符,因此需要进行转义

gsub("\\[|\\]", "", df$Songs)

Or other way is

或者其他方式

gsub("[][]", "", df$Songs)