Split a character vector into individual characters? (opposite of paste or stringr::str_c)

前端 未结 2 949
情歌与酒
情歌与酒 2020-11-28 15:44

An incredibly basic question in R yet the solution isn\'t clear.

How to split a vector of character into its individual characters, i.e. the opposite of paste(

2条回答
  •  伪装坚强ぢ
    2020-11-28 16:29

    Yes, strsplit will do it. strsplit returns a list, so you can either use unlist to coerce the string to a single character vector, or use the list index [[1]] to access first element.

    x <- paste(LETTERS, collapse = "")
    
    unlist(strsplit(x, split = ""))
    # [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
    #[20] "T" "U" "V" "W" "X" "Y" "Z"
    

    OR (noting that it is not actually necessary to name the split argument)

    strsplit(x, "")[[1]]
    # [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
    #[20] "T" "U" "V" "W" "X" "Y" "Z"
    

    You can also split on NULL or character(0) for the same result.

提交回复
热议问题