从特定长度中删除字符

Removing character from specific length

我有一列如下:

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

我想删除字符以作为流程:

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

你愿意帮我吗? 提前致谢

您可以使用 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

数据:

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))

另一个选项:

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

另一种方法是提取所有内容直到冒号 (:)

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