【问题标题】:Split a character vector into individual characters? (opposite of paste or stringr::str_c)将字符向量拆分为单个字符? (与 paste 或 stringr::str_c 相对)
【发布时间】:2014-04-12 10:01:25
【问题描述】:

R 中一个令人难以置信的基本问题,但解决方案尚不清楚。

如何将字符向量拆分为单个字符,即paste(..., sep='')stringr::str_c() 的反面?

比这更不笨重的东西:

sapply(1:26, function(i) { substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",i,i) } )
"A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"

能否以其他方式完成,例如strsplit()stringr::* 或其他什么?

【问题讨论】:

  • 我的目的是为迭代器生成内容:it = iter(sapply(1:26, function(i) { substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",i,i) } )) ... nextElem(it)
  • @Henrik 非常感谢,但这只是一个更通用的例子。

标签: string r paste string-split stringr


【解决方案1】:

是的,strsplit 会这样做。 strsplit 返回一个列表,因此您可以使用 unlist 将字符串强制转换为单个字符向量,或者使用列表索引 [[1]] 访问第一个元素。

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(注意实际上没有必要命名 split 参数)

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"

您也可以拆分NULLcharacter(0) 以获得相同的结果。

【讨论】:

    【解决方案2】:

    来自stringrstr_extract_all() 提供了一种执行此操作的好方法:

    str_extract_all("ABCDEFGHIJKLMNOPQRSTUVWXYZ", boundary("character"))
    
    [[1]]
     [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U"
    [22] "V" "W" "X" "Y" "Z"
    

    【讨论】:

      【解决方案3】:

      为了清晰起见,这是逐步呈现的;实际上,会创建一个函数。

      查找任何字符按顺序重复的次数

      the_string <- "BaaaaaaH"
      # split string into characters
      the_runs <- strsplit(the_string, "")[[1]]
      # find runs
      result <- rle(the_runs)
      # find values that are repeated
      result$values[which(result$lengths > 1)]
      #> [1] "a"
      # retest with more runs
      the_string <- "BaabbccH"
      # split string into characters
      the_runs <- strsplit(the_string, "")[[1]]
      # find runs
      result <- rle(the_runs)
      # find values that are repeated
      result$values[which(result$lengths > 1)]
      #> [1] "a" "b" "c"
      

      【讨论】:

      • 不,我没有要求运行长度编码,我只是说“将字符向量拆分为单个字符”。所以"BaabbccH" 应该给出'B'、'a'、'a'、'b'、'b'、'c'、'c'、'H'。
      • @smci 是的,不知道是什么让我分心了。
      猜你喜欢
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2014-10-21
      • 1970-01-01
      • 2021-11-17
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多