简体   繁体   中英

How to pass the length of each element in an R vector to the substr function?

I have the following vector.

v <- c('X100kmph','X95kmph', 'X90kmph', 'X85kmph', 'X80kmph',
       'X75kmph','X70kmph','X65kmph','X60kmph','X55kmph','X50kmph',
       'X45kmph','X40kmph','X35kmph','X30kmph','X25kmph','X20kmph',
       'X15kmph','X10kmph')

I want to extract the digits representing speed. They all start at the 2nd position, but end at different places, so I need (length of element i) - 4 as the ending position.

The following doesn't work as length(v) returns the length of the vector and not of each element.

vnum <- substr(v, 2, length(v)-4)

Tried lengths() as well, but doesn't work.

How can I supply the length of each element to substr ?

Context :

v actually represents a character column (called Speed ) in a tibble which I'm trying to mutate into the corresponding numeric column.

mytibble <- mytibble %>%
  mutate(Speed = as.numeric(substr(Speed, 2, length(Speed) - 4)))

Using nchar() instead of length() as suggested by tmfmnk does the trick!

vnum <- substr(v, 2, nchar(v)-4)

If you just want to extract the digits, then here is another option

vnum <- gsub("\\D","",v)

such that

> vnum
 [1] "100" "95"  "90"  "85"  "80"  "75"  "70"  "65"  "60"  "55" 
[11] "50"  "45"  "40"  "35"  "30"  "25"  "20"  "15"  "10" 

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