将字符串转换为R中的序列

use*_*945 3 parsing r

我正在读表格的R表

SUB DEP
1   ""
2   "1"
3   "1, 2"
4   "1, 2, 3"
5   "1:3, 5"
Run Code Online (Sandbox Code Playgroud)

然后我将DEP变量解析为数字列表,如下所示:

Dependencies <- read.table("dependencies.txt", header = TRUE,
                           colClasses = c("numeric", "character"),
                           fill = TRUE)
Dependencies$DEP <- strsplit(Dependencies$DEP, ", ")
Dependencies$DEP <- lapply(Dependencies$DEP, as.numeric)
Run Code Online (Sandbox Code Playgroud)

这工作正常,除了当读入的文件包含序列时,例如在行5中. as.numeric("1:3")返回NA,而不是1,2,3.我应该如何将字符串"1:3, 5"转换为数字向量c(1,2,3,5) ).我可以改变向量在输入文件中的写入方式,如果有帮助的话.

谢谢您的帮助!迈克尔

A5C*_*2T1 7

这是一个使用可怕eval(parse(...))结构的解决方案:

Dependencies$DEP <- sapply(paste("c(", Dependencies$DEP, ")"), 
                           function(x) eval(parse(text = x)))
Dependencies
#   SUB        DEP
# 1   1       NULL
# 2   2          1
# 3   3       1, 2
# 4   4    1, 2, 3
# 5   5 1, 2, 3, 5
str(Dependencies)
# 'data.frame':  5 obs. of  2 variables:
# $ SUB: int  1 2 3 4 5
# $ DEP:List of 5
# ..$ c(  )       : NULL
# ..$ c( 1 )      : num 1
# ..$ c( 1, 2 )   : num  1 2
# ..$ c( 1, 2, 3 ): num  1 2 3
# ..$ c( 1:3, 5 ) : num  1 2 3 5
Run Code Online (Sandbox Code Playgroud)


use*_*452 5

在这种情况下,您可以将您的参数强制转换为dget可以处理的表单

aTxt <- 'SUB DEP
1   ""
2   "1"
3   "1, 2"
4   "1, 2, 3"
5   "1:3, 5
'
Dependencies <- read.table(text = aTxt, header = TRUE,
                           colClasses = c("numeric", "character"),
                           fill = TRUE)
Dependencies$DEP <- sapply(Dependencies$DEP, function(x) dget(textConnection(paste('c(', x, ')'))))

> Dependencies
  SUB        DEP
1   1       NULL
2   2          1
3   3       1, 2
4   4    1, 2, 3
5   5 1, 2, 3, 5
Run Code Online (Sandbox Code Playgroud)