简体   繁体   中英

Extracting part of a string (for a vector of strings)

x<-c("123-12","12-24","6-4")

How do I extract the portion of each string before the dash into a new vector? In this example my result should be equivalent to

c("123","12","6")

How do I do the same thing, except extract everything after the dash? Ie

c("12","24","4")

For my problem, you can assume that every element of x will have one and only one dash.

For extracting the string before the dash, replace the dash and everything after by an empty character string.

sub('-.*', '', x)

For extracting the string after the dash, do the opposite

sub('.*-', '', x)

This is another way, with the added benefit off converting the values to a numeric type:

d <- read.table(text=x, sep='-')
#    V1 V2
# 1 123 12
# 2  12 24
# 3   6  4

Then we have:

d[,1]
# [1] 123  12   6
d[,2]
# [1] 12 24  4

You can use a combination of strsplit and lapply :

Before dash:

b <- unlist(lapply(strsplit(x, "-"), function(x) x[1]))
> b
[1] "123" "12"  "6" 

After dash:

a <- unlist(lapply(strsplit(x, "-"), function(x) x[2]))
> a
"12" "24" "4"  

尝试这个:

substr(x,1,as.vector(regexpr("-",x))-1)

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