【发布时间】: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 中有以下指令:
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,但仍然得到一个空列表。 有什么帮助吗?
【问题讨论】:
已纳入 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
【讨论】:
scan 有一个 text 正式的。
what 参数的使用是文本格式的规范。但也许我的编辑解决了你的观点?
read.table 和表兄弟们就是这样被提出这个论点的,不是吗?
! is.na 而不是na.omit。结果发现索引方式稍微快了一点......令人惊讶。