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

R 将字符串向量转换为整数向量,r,R,以下工作如预期: > as.integer(c("2","3")) [1] 2 3 但是当我尝试(使用stringr包)时: 有没有其他方法可以将形式为“55,66,77”的字符串转换为包含这三个数字的向量? 我是一个完全的新手,任何关于这方面的文档提示都将不胜感激。str\u split返回一个列表。您必须访问正确的列表元素: as.integer(unlist(strsplit("55,66,77",","))) as.integer(str_split("55,66,77",",

以下工作如预期:

> as.integer(c("2","3"))
[1] 2 3
但是当我尝试(使用stringr包)时:

有没有其他方法可以将形式为“55,66,77”的字符串转换为包含这三个数字的向量?
我是一个完全的新手,任何关于这方面的文档提示都将不胜感激。

str\u split
返回一个列表。您必须访问正确的列表元素:

as.integer(unlist(strsplit("55,66,77",",")))
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

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

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

v为什么不使用
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

x非常感谢,真是太快了。我以为列表是向量。列表是(通用)向量,但不是可以强制为整数的向量。
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