Ben
Ben

Reputation: 21705

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? I.e.

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

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

Upvotes: 0

Views: 900

Answers (4)

Matthew Plourde
Matthew Plourde

Reputation: 44634

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

Upvotes: 2

zx8754
zx8754

Reputation: 56259

Try this:

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

Upvotes: 0

Erich Studerus
Erich Studerus

Reputation: 557

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)

Upvotes: 3

tcash21
tcash21

Reputation: 4995

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"  

Upvotes: 1

Related Questions