简体   繁体   中英

Eliminating characters within columns R

I have a dataframe with a column as follows:

x = data.frame("A" = c("93 VLC", "43 VLC", "73 VLC"))

I am trying to modify the column "A" to eliminate the "VLC" and just keep the number.

I would like the output to be:

x = data.frame("A" = c(93, 43, 73))

Is there a way to do this? thanks

If we need to extract the numeric part, use parse_number

x$A <- readr::parse_number(x$A)
x$A
#[1] 93 43 73

Or using trimws

as.numeric(trimws(x$A, whitespace = "\\D+"))
#[1] 93 43 73

Or using sub

as.numeric(sub("\\s*\\D+$", "", x$A))

You can use str_remove() from the stringr library:

library(dplyr)
library(stringr)

x = data.frame("A" = c("93 VLC", "43 VLC", "73 VLC"))

x %>%
  mutate(A = str_remove(A, ' VLC'))

#   A
# 1 93
# 2 43
# 3 73

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