从特定长度删除字符

问题描述

我在下面有专栏:

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"