简体   繁体   中英

R using special characters

I have a column of strings (and NAs) in a dataset whose values look like:

"85min"  "1hr 19min"  "98min"  NA  "119min"  "105min"  NA  "1hr 30min"

I'm trying to change all of the values to numerics (in minutes), so that the values look like:

85  79  98  NA  119  105  NA  90

I tried to do it by pieces, first removing the "min," then removing the "hr," then changing "1" to "60," and then changing the middle spaces to plus signs, giving me:

"85"  "60+19"  "98"  NA  "119"  "105"  NA  "60+30"

I was hoping that by applying as.numeric, I would get the ones with "+" signs to turn into formulas, but instead they just resulted in NAs.

Is there any shorthand way of doing this kind of conversion? Many thanks in advance!

Yes, you need parse and eval

strings = c("85",  "60+19",  "98",  NA,  "119",  "105",  NA,  "60+30")
sapply(parse(text=strings), eval)
[1]  85  79  98  NA 119 105  NA  90

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