Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...