将角色放在角色的左侧

时间:2013-03-20 01:55:40

标签: r

给出一些数据

hello <- c('13.txt','12.txt','14.txt')

我想取数字并转换为数字,即删除.txt

4 个答案:

答案 0 :(得分:7)

您需要file_path_sans_ext

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

答案 1 :(得分:5)

您可以使用原始帖子中“hello”对象上的函数gsub使用正则表达式执行此操作。

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

答案 2 :(得分:3)

另一种正则表达式解决方案

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

答案 3 :(得分:1)

如果您知道自己的扩展名均为.txt,那么您可以使用substr()

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