2016-08-03 46 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" 
相關問題