简体   繁体   中英

How to create a new character column removing text from another column in dataframe in r

I have the following data frame in R

East    24  Consumer    7/18/2018 0:00  Second Class    Pennsylvania    Chairs  USD71.37
East    29  Consumer    9/21/2016 0:00  Standard Class  Pennsylvania    Binders USD9.61
East    33  Consumer    9/21/2016 0:00  Standard Class  Pennsylvania    Binders USD6.85
East    199 Corporate   7/13/2018 0:00  Standard Class  Pennsylvania    Binders USD2.94
East    216 Corporate   1/9/2016 0:00   Standard Class  Ohio    Machines    USD1188
East    222 Consumer    12/27/2016 0:00 First Class Ohio    Binders USD24
East    224 Consumer    12/27/2016 0:00 First Class Ohio    Machines    USD252
East    331 Consumer    9/1/2017 0:00   First Class Pennsylvania    Binders USD28
East    333 Consumer    4/29/2017 0:00  Second Class    Pennsylvania    Binders USD40
East    334 Consumer    4/29/2017 0:00  Second Class    Pennsylvania    Binders USD8

We could use parse_number<\/code> function from readr<\/code> package:

library(dplyr)
library(readr)

df %>% 
  mutate(newCol = parse_number(V10))

If the column is called "a", you can sub set the string and then convert to numeric like this:

> a <- c("USD71.37","USD9.61")
> 
> as.numeric(str_sub(a,4,-1))
[1] 71.37  9.61

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