error in strsplit when trying to separate by a comma

前端 未结 2 2002
半阙折子戏
半阙折子戏 2020-12-03 23:59

I have the vector

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

and I want to separate them by the comma to eventually make

相关标签:
2条回答
  • 2020-12-04 00:21

    Your "length" object is a factor:

    As the error message indicates, strsplit expects a character vector as the input.

    Try:

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

    Demo

    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"
    
    0 讨论(0)
  • 2020-12-04 00:23

    You could also use: (x from @Ananda Mahto's post)

     library(stringr)
     str_split(x, ",")
     #[[1]]
     # [1] "1" "2"
    
     #[[2]]
     #[1] "3" "4"
    
     #[[3]]
     #[1] "5" "6"
    

    Or

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

    Or

     library(stringi)
     stri_extract_all_regex(x, "[0-9]+")
    
    0 讨论(0)
提交回复
热议问题