以下按预期工作:
> 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'
有没有其他方法将形式为"53,56,77"的字符串转换为具有这三个数字的向量?我是一个完整的新手,任何有关此文档的提示都将受到高度赞赏.
如果你有一个字符串向量并希望每个字符串的值,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
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