2013-03-20 30 views

回答

5

您可以使用原始帖子中「hello」對象上的函數gsub使用正則表達式執行此操作。

hello <- c('13.txt','12.txt','14.txt') 
as.numeric(gsub("([0-9]+).*","\\1",hello)) 
#[1] 13 12 14 
7

你想file_path_sans_exttools

library(tools) 
hello <- c('13.txt','12.txt','14.txt') 
file_path_sans_ext(hello) 
## [1] "13" "12" "14" 
+0

感謝。由於某種原因,我無法在當前的安裝程序上安裝該軟件包,還有另一種使用基本R語法的方法嗎? – luke123 2013-03-20 02:05:24

+0

@ luke123 - 'tools'是標準R分佈的一部分。您不應該安裝它,只需致電庫 – mnel 2013-03-20 02:06:13

+0

@mnel最近自己發現了這一個,並且只是爲了這些情況而喜歡它。 +1 – 2013-03-20 02:49:29

3

另一個正則表達式的解決方案

hello <- c("13.txt", "12.txt", "14.txt") 
as.numeric(regmatches(hello, gregexpr("[0-9]+", hello))) 
## [1] 13 12 14 
1

如果你知道你的擴展都.txt那麼你可以使用substr()

> hello <- c('13.txt','12.txt','14.txt') 
> as.numeric(substr(hello, 1, nchar(hello) - 3)) 
#[1] 13 12 14 
相關問題