只返回独特的词

标签 r string function

<分区>

假设我有一个字符串,我只希望句子中的唯一单词作为单独的元素

 a = "an apple is an apple"
word <- function(a){
  
  words<- c(strsplit(a,split = " "))
  return(unique(words))
}

word(a)

返回

[[1]]
[1] "an"    "apple" "is"    "an"    "apple"

我期望的输出是

'an','apple','is'

我做错了什么?非常感谢任何帮助

干杯!

最佳答案

问题是将strsplit(.)包裹在c(.)中并没有改变它仍然是一个列表的事实,和 unique 将在列表级而不是单词级运行。

c(strsplit(rep(a, 2), "\\s+"))
# [[1]]
# [1] "an"    "apple" "is"    "an"    "apple"
# [[2]]
# [1] "an"    "apple" "is"    "an"    "apple"
unique(c(strsplit(rep(a, 2), "\\s+")))
# [[1]]
# [1] "an"    "apple" "is"    "an"    "apple"

备选方案:

  1. 如果length(a)总是1,那么也许

    unique(strsplit(a, "\\s+")[[1]])
    # [1] "an"    "apple" "is"   
    
  2. 如果 length(a) 可以是 2 或更多,并且您想要每个句子的唯一单词列表,那么

    a2 <- c("an apple is an apple", "a pear is a pear", "an orange is an orange")
    lapply(strsplit(a2, "\\s+"), unique)
    # [[1]]
    # [1] "an"    "apple" "is"   
    # [[2]]
    # [1] "a"    "pear" "is"  
    # [[3]]
    # [1] "an"     "orange" "is"    
    

    (注意:这总是返回一个列表,不管输入中的句子数量是多少。)

  3. 如果 length(a) 可以是 2 或更多,并且您希望在所有句子中有一个独特的词,那么

    unique(unlist(strsplit(a2, "\\s+")))
    # [1] "an"     "apple"  "is"     "a"      "pear"   "orange"
    

    (注意:当length(a)为1时,此方法也能正常工作。)

关于只返回独特的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72476742/

相关文章:

r - 通过合并数据框中以 "-"分隔的多个列来创建新列

r - 使用 R - 如何将 2 个气泡图集成到一个图中

r - RStudio Server 的共享库出错

JavaScript 搜索特定字符串

c# - 如何使用 float.Parse 从 "5/2"等字符串中获取小数

php - 在 linux 中的 bash 的 .sh 之类的脚本中使用 php 和 perl 以及 R 等等?是否可以?

algorithm - 字符串的压缩算法

ios - Swift 将数组中的所有元素加在一起

c++ - 在函数内部调用函数

function - Julia Do 函数的语法是如何工作的?