Hossein
Hossein

Reputation: 19

Removing character from specific length

I have a column as bellow:

a)1902-2019: -1.05 mm/yr
b)1902-1961: -0.79 mm/yr
c)1962-2019: -1.43 mm/yr

I want to remove character to be as flow:

a)1902-2019
b)1902-1961
c)1962-2019

Would you mind to help me? Thanks in advance

Upvotes: 0

Views: 43

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388982

Another way would be to extract everything until a colon (:)

sub('(.*):.*', '\\1', df$V1)
#[1] "1902-2019" "1902-1961" "1962-2019"

Upvotes: 0

AlexB
AlexB

Reputation: 3269

Another option:

x <- '1962-2019: -1.43 mm/yr'
gsub(':.*', "", x)

Upvotes: 1

jay.sf
jay.sf

Reputation: 72919

You may use substr.

df1 <- transform(df1, V3=substr(V1, 1, 9))
df1
#                       V1         V2        V3
# 1 1902-2019: -1.05 mm/yr  1.1088551 1902-2019
# 2 1902-1961: -0.79 mm/yr -0.1593216 1902-1961
# 3 1962-2019: -1.43 mm/yr  0.5811273 1962-2019

Data:

df1 <- structure(list(V1 = c("1902-2019: -1.05 mm/yr", "1902-1961: -0.79 mm/yr", 
"1962-2019: -1.43 mm/yr"), V2 = c(0.0958290168309483, 2.00653802357232, 
0.961576240476421)), class = "data.frame", row.names = c(NA, 
-3L))

Upvotes: 1

Related Questions