尝试用逗号分隔时strsplit中的错误

时间:2014-09-29 18:18:08

标签: r strsplit

我有矢量

length
# [1] 15,34, 12,24, 225,
# Levels: 12,24, 15,34, 225,

我希望用逗号分隔它们,最终制作这些值的列表

尝试:

strsplit(length, ",") 

但不断收到错误消息

Error in strsplit(length, ",") : non-character argument

2 个答案:

答案 0 :(得分:11)

您的“长度”对象是factor

如错误消息所示,strsplit需要一个字符向量作为输入。

尝试:

strsplit(as.character(length), ",") 

演示

x <- factor(c("1,2", "3,4", "5,6"))
strsplit(x, ",")
# Error in strsplit(x, ",") : non-character argument
strsplit(as.character(x), ",")
# [[1]]
# [1] "1" "2"
# 
# [[2]]
# [1] "3" "4"
# 
# [[3]]
# [1] "5" "6"

答案 1 :(得分:1)

你也可以使用:( x来自@Ananda Mahto的帖子)

 library(stringr)
 str_split(x, ",")
 #[[1]]
 # [1] "1" "2"

 #[[2]]
 #[1] "3" "4"

 #[[3]]
 #[1] "5" "6"

或者

  str_extract_all(x, "[0-9]+")

或者

 library(stringi)
 stri_extract_all_regex(x, "[0-9]+")