【问题标题】:converting a string from csv to a vector of numbers in R将字符串从csv转换为R中的数字向量
【发布时间】:2012-12-12 07:45:30
【问题描述】:

我在 R 中有以下指令:

y <- rep(1:2,each=3)

我知道它会生成一个 1 和 2 的向量:

[1] 1 1 1 2 2 2

如果我想从具有以下格式的 csv 行中提取该信息,如何获得相同的结果:

[1] ",,1,1,1,2,2,2"

我已尝试使用 as.numeric 和 is.na,但仍然得到一个空列表。 有什么帮助吗?

【问题讨论】:

    标签: r list csv


    【解决方案1】:

    已纳入 MatthewPlourde 建议:

    > txt <- ",,1,1,1,2,2,2"
    > scan(text=txt,, sep=",")
    Read 8 items
    [1] NA NA  1  1  1  2  2  2
    

    其他选项是 strsplit。

    > unlist( strsplit(txt, ",") )
    [1] ""  ""  "1" "1" "1" "2" "2" "2"
    

    采用 Matthew 的建议后,无需回答“如何转换为数字?”的问题。 .... 但是如果你有一个字符向量,它会是......现在你已经分成组件,使用as.numeric

    > as.numeric( scan(textConnection(txt), what="", sep=",") )
    Read 8 items
    [1] NA NA  1  1  1  2  2  2
    

    另一种选择是使用数字格式扫描读取:

    > scan(textConnection(txt), what=numeric(0), sep=",")
    Read 8 items
    [1] NA NA  1  1  1  2  2  2
    

    并删除 NA:

    > numbas <- scan(textConnection(txt), what=numeric(0), sep=",")
    Read 8 items
    > numbas[!is.na(numbas)]
    [1] 1 1 1 2 2 2
    

    【讨论】:

    • 感谢@DWin,但我想将我得到的行 [1] ",,1,1,1,2,2,2" 转换为 [1] 1 1 1 2 2 2
    • @DWin +1。仅供参考,scan 有一个 text 正式的。
    • @MatthewPlourde:我不确定我是否理解你的观点。我对what 参数的使用是文本格式的规范。但也许我的编辑解决了你的观点?
    • 啊哈。是的,@马修。现在我想起来了……read.table 和表兄弟们就是这样被提出这个论点的,不是吗?
    • 我很好奇你为什么选择! is.na 而不是na.omit。结果发现索引方式稍微快了一点......令人惊讶。
    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 2014-09-10
    • 2016-05-03
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多