Seydou GORO
Seydou GORO

Reputation: 1285

How to drop a particular element among others in a string

ID<-c(1:5)
string<-c("aaa-NA","NA", "bbb-NA-aaa,","bbb-ccc","NA-aaa-ccc")
mydata<-data.frame(ID,string)

I want to create a new variable by dropping NA, only when they are associated with other characters, like that:

  ID      string new_var
1  1      aaa-NA     aaa
2  2          NA      NA
3  3 bbb-NA-aaa, bbb-aaa
4  4     bbb-ccc bbb-ccc
5  5  NA-aaa-ccc aaa-ccc

Upvotes: 1

Views: 28

Answers (1)

Peace Wang
Peace Wang

Reputation: 2419

mydata$new_var <- gsub("-NA|NA-","",mydata$string)

Upvotes: 2

Related Questions