user15032839
user15032839

Reputation: 93

Find and replace text with pattern in R

I have a df here below and I need to delete under only the column FRUIT that contains any text with [...]. Please see my df

DATE FRUIT LOCATION VALUE
2010-01-01 Apple [111-112, 1100, 1151-1152] USA 2
2010-01-01 Pinapple [22] USA 12

so ideally I want my df to look like this

DATE FRUIT LOCATION VALUE
2010-01-01 Apple USA 2
2010-01-01 Pinapple USA 12

I tried to use gsub, but it is not working out.

df$FRUIT<-gsub("[*]", "", df$FRUIT)

Upvotes: 0

Views: 31

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101129

Perhaps you can try gsub like below

df$FRUIT <- gsub("\\s\\[.*\\]","",df$FRUIT)

and you will get

> df
        DATE    FRUIT LOCATION VALUE
1 2010-01-01    Apple      USA     2
2 2010-01-01 Pinapple      USA    12

Data

> dput(df)
structure(list(DATE = c("2010-01-01", "2010-01-01"), FRUIT = c("Apple [111-112, 1100, 1151-1152]",
"Pinapple [22]"), LOCATION = c("USA", "USA"), VALUE = c(2L, 12L
)), class = "data.frame", row.names = c(NA, -2L))

Upvotes: 0

Related Questions