【问题标题】:Convert single string to numeric vector in R [duplicate]将单个字符串转换为R中的数字向量[重复]
【发布时间】:2020-04-22 15:05:50
【问题描述】:

我正在尝试使用readline 来允许用户输入要使用的索引的数字向量,例如c(1, 2, 10)c(1:1300, 1500:2000),但我无法将返回的字符转换为数字向量。我在this 帖子中看到了如何为c(1, 2, 10) 之类的特定枚举向量执行此操作,但是将这种方法用于c(1:1300, 1500:2000) 之类的东西是非常不切实际的。有没有一种不涉及一堆条件字符串拆分的通用方法?就像,我可以看到像下面的伪代码这样的东西是如何工作的,似乎应该有一个更自然的方法。

# pseudo-code
string.convert <- function(s){
    split0 = strip c() from s
    split1 = elements of split0 split by commas
    split2 = elements of split1 split by colons
    split3 = apply as.numeric to elements of split2
    split4 = insert integers between elements of split3 conditional on colon separation 
    return(concatenated results of split4)
}

【问题讨论】:

    标签: r type-conversion character numeric


    【解决方案1】:

    啊,我刚刚想通了。

    eval(parse(text='1:5'))

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 2012-12-08
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多