简体   繁体   中英

R recode a column based on a string value

I have a dataframe as follows

date     volume
1-1-90    1.1M
2-1-90     200
3-1-90     0.5M
4-1-90    100
5-1-90     1M

The values with M means in millions. I would like to detect the values with letter M or m in them and transform these values into the numerical equivalents

date     volume
1-1-90    1100000
2-1-90     200
3-1-90     500000
4-1-90    100
5-1-90    10000000

Is there a nifty way of doing it in R?

I have used an ifelse condition as follows

(df)[, Volumes := ifelse(volume %in% c("m", "M"),volume * 1000000,0)]

but this does not seem to work. Am sure am overlooking which must be trivial.

> dat$volume <- ifelse( grepl("M|m" ,dat$volume), 
                             1e6*as.numeric(sub("M|m","", dat$volume)), 
                             as.numeric(as.character(dat$volume) ) )
> dat
    date  volume
1 1-1-90 1100000
2 2-1-90     200
3 3-1-90  500000
4 4-1-90     100
5 5-1-90 1000000

It seems to me like you have a data.table object there (or maybe you mistakenly using data.table syntax on a data.frame ?)

Anyway, if df is a data.table object, I would go with

df[grepl("m", volume, ignore.case = T), 
   volume2 := as.numeric(gsub("m", "", volume, ignore.case = T)) * 1e6]
df[is.na(volume2), volume2 := as.numeric(as.character(volume))][, volume := NULL]
df
#      date volume2
# 1: 1-1-90 1100000
# 2: 2-1-90     200
# 3: 3-1-90  500000
# 4: 4-1-90     100
# 5: 5-1-90 1000000

The stringr package can also work here:

require(stringr)

dat$volume <- ifelse(str_sub(dat$volume, -1) == "M"
                     ,as.numeric(str_sub(dat$volume, 0, nchar(dat$volume)-1))*1000000
                     ,dat$volume)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM