将字符串向量转换为整数向量

时间:2013-12-22 17:38:40

标签: r

以下按预期方式工作:

> as.integer(c("2","3"))
[1] 2 3

但是当我尝试(使用stringr包)时:

> str_split("55,66,77",",")
[[1]]
[1] "55" "66" "77"
> as.integer(str_split("55,66,77",","))
Error: (list) object cannot be coerced to type 'integer'

有没有其他方法可以将“556,77”形式的字符串转换为具有这三个数字的向量? 我是一个完整的新手,任何有关此文档的提示都将受到高度赞赏。

4 个答案:

答案 0 :(得分:17)

str_split返回一个列表。您必须访问正确的列表元素:

as.integer(str_split("55,66,77",",")[[1]]) ## note the [[1]]
# [1] 55 66 77

或者您可以使用unlist将完整列表转换为矢量:

as.integer(unlist(strsplit("55,66,77",",")))
# [1] 55 66 77

答案 1 :(得分:7)

如果您有一个字符串向量并想要每个字符串的值,lapply将遍历列表:

v <- c("55,66,77", "1,2,3")
lapply(str_split(v, ','), as.integer)
## [[1]]
## [1] 55 66 77
## 
## [[2]]
## [1] 1 2 3

答案 2 :(得分:4)

as.integer(unlist(strsplit("55,66,77",",")))

答案 3 :(得分:3)

为什么不使用scan?如果所有数据都是以逗号分隔的整数开头,则结果将是整数向量,从而无需在以后使用as.integer

x <- "55,66,77"
y <- scan(text = x, what = 0L, sep=",")
# Read 3 items
y
#  [1] 55 66 77
str(y)
#  int [1:3] 55 66 77

使用多个值,您可以选择是否需要单个向量或向量列表:

v <- c("55,66,77", "1,2,3")
scan(text = v, what = 0L, sep=",")
# Read 6 items
# [1] 55 66 77  1  2  3
lapply(seq_along(v), function(z) scan(text = v[z], what = 0L, sep = ","))
# Read 3 items
# Read 3 items
# [[1]]
# [1] 55 66 77
# 
# [[2]]
# [1] 1 2 3

如果您不希望收到有关读取了多少值的消息,请将quiet = TRUE添加到scan

相关问题