A380
A380

Reputation: 59

How to use multiple conditions for regex using ifelse?

i am trying to extract and replace '?'in the client column if it matches the group = SA with 'AWS' as client instead of '?'. Here '?' can be '?' or '?????' or ??. However it seems not to work. Can someone help on this issue? I am using R

Thanks

test[,Client:=ifelse(Group=='SA'&Client==grepl('\\?+',Client,perl = T),'AWS',Client)]

sample data

client<-c('?','???','????')
GROUP<-c('SA','SA','SA')
df <- melt(data.frame(client,GROUP))

final result should look like

Client GROUP
AWS     SA

Upvotes: 0

Views: 83

Answers (1)

Biblot
Biblot

Reputation: 705

It seems you are mixing data.table syntax with data frames. data.table is used like this:

DT[i, j, by] 

To replace values from a subset of a data.table, first declare your subset in i, then operate on your columns in j. You first want to select all rows where GROUP == "SA", then replace one or more ? by AWS, if I understood your problem correctly.

library(data.table)
library(stringr)

client<-c('?','???','????')
GROUP<-c('SA','SA','SA')
dt <- data.table(client,GROUP)

dt[GROUP == "SA", client := str_replace(client, "\\?+", "AWS")]
#    client GROUP
# 1:    AWS    SA
# 2:    AWS    SA
# 3:    AWS    SA

Upvotes: 3

Related Questions