【问题标题】:Removing character from specific length从特定长度中删除字符
【发布时间】:2020-12-12 02:32:28
【问题描述】:
我有一个专栏如下:
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
你愿意帮助我吗?
提前致谢
【问题讨论】:
标签:
r
numbers
element
string-length
removing-whitespace
【解决方案1】:
另一种选择:
x <- '1962-2019: -1.43 mm/yr'
gsub(':.*', "", x)
【解决方案2】:
您可以使用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))
【解决方案3】:
另一种方法是提取所有内容,直到冒号 (:)
sub('(.*):.*', '\\1', df$V1)
#[1] "1902-2019" "1902-1961" "1962-2019"