A.J
A.J

Reputation: 1180

Changing value based on a condition in r

I have the following dataframe

head(data)
      Date Avg.Join.Delay Min.Join.Dely Max.Join.Dely    ACCOUNT STB_TYPE  MARKET
1 6/5/2015            500           500           500 3036831961  IPH8005  Denver
2 6/5/2015            500           500           500 3038416736  IPH8005  Denver
3 6/5/2015            500           500           500 4802192190  IPH8005 Phoenix
4 6/5/2015            500           500           500 4802193088  IPH8005 Phoenix
5 6/5/2015            500           500           500 4802795632  IPH8005 Phoenix
6 6/5/2015            500           500           500 4803611713  IPH8005 Phoenix

I want to change the Account number to a City/State (303 = Colorado), but I am not sure what is the correct syntax of this kind of script.

I tried data$ACCOUNT[data$ACCOUNT == "303%"] <- "Colorado" but it doesn't change the value. Any idea how to do it in a way that it will change all the values that begin with xxx?

Upvotes: 1

Views: 97

Answers (1)

akrun
akrun

Reputation: 887118

You can try using substr to extract the first 3 characters

data$ACCOUNT[substr(data$ACCOUNT,1,3)=='303'] <- 'Colorado'

Or use sub

data$ACCOUNT[sub('(.{3}).*', '\\1',data$ACCOUNT)=='303'] <- 'Colorado'

Or grep

data$ACCOUNT[grepl('^303', data$ACCOUNT)] <- 'Colorado'

Upvotes: 1

Related Questions