2016-08-03 45 views
7

我需要提取字符串中的前2个字符以便稍后创建bin plot分布。 载体:提取字符串中的前2个字符

x <- c("75 to 79", "80 to 84", "85 to 89") 

我有这个迄今为止得到:

substrRight <- function(x, n){ 
    substr(x, nchar(x)-n, nchar(x)) 
} 

调用函数

substrRight(x, 1) 

响应

[1] "79" "84" "89" 

需要打印的最后2个字符不是冷杉吨。

[1] "75" "80" "85" 

回答

15

您可以只使用substr功能直接把每个字符串的前两个字符:

x <- c("75 to 79", "80 to 84", "85 to 89") 
substr(x, start = 1, stop = 2) 
# [1] "75" "80" "85" 

你也可以写一个简单的功能做一个“反向”子,给人“开始”和‘停止’假定索引值开始于字符串的结尾:

revSubstr <- function(x, start, stop) { 
    x <- strsplit(x, "") 
    sapply(x, 
     function(x) paste(rev(rev(x)[start:stop]), collapse = ""), 
     USE.NAMES = FALSE) 
} 
revSubstr(x, start = 1, stop = 2) 
# [1] "79" "84" "89" 
0

使用gsub ...

x <- c("75 to 79", "80 to 84", "85 to 89") 

gsub(" .*$", "", x) # Replace the rest of the string after 1st space with nothing 
[1] "75" "80" "85" 
相关问题