简体   繁体   English

不适用于R中的列表

[英]lapply not iterating through list in R

I have a list of character strings where there are repeats in some of the strings. 我有一个字符串列表,其中某些字符串中有重复项。 For example: 例如:

   [[1]]
   [1] "gr gal gr gal"

   [[2]]
   [1] "gr gal"

   [[3]]
   [1] "gr gal ir ol"

   [[4]]
   [1] "gr gal gr gal"

   [[5]]
   [1] "gr gal"

My desired output is: 我想要的输出是:

   [[1]]
   [1] "gr gal"

   [[2]]
   [1] "gr gal"

   [[3]]
   [1] "gr gal ir ol"

   [[4]]
   [1] "gr gal"

   [[5]]
   [1] "gr gal"

Where the repeats are removed from the string. 从字符串中删除重复项的位置。

My plan is to call strsplit(x, split = " ") and then call the unique function on the split object. 我的计划是调用strsplit(x,split =“”),然后在split对象上调用唯一函数。 If I do it choosing 1 member of the list, my code works fine: 如果我选择列表的1个成员,则我的代码可以正常工作:

  > strsplit(pathmd1[[76]], split = " ")
  [[1]]
  [1] "gr" "gal" "gr" "gal"

  > splittest <- strsplit(pathmd1[[76]], split = " ")
  > unique(unlist(splittest))
  [1] "gr" "gal"

However, when I use lapply using these functions, an error is thrown 但是,当我通过这些函数使用lapply时,会引发错误

    pathmd2 <- lapply(1:length(pathmd1), function(i) strsplit(pathmd1[[i]], 
               split = " "))
    pathmd <- lapply(1:length(pathmd2), function(i) unique(pathmd2[[i]])

    unexpected symbol
    77: pathmd2 <- lapply(1:length(pathmd1), function(i) 
        strsplit(pathmd1[[i]], split = " ")
    78: pathmd
        ^

Why isn't the function working with lapply? 为什么函数不能与lapply一起使用?

You can try: 你可以试试:

lapply(f, function(x) unique(unlist(strsplit(x, " "))))
#output
[[1]]
[1] "gr"  "gal"

[[2]]
[1] "gr"  "gal"

[[3]]
[1] "gr"  "gal" "ir"  "ol" 

[[4]]
[1] "gr"  "gal"

[[5]]
[1] "gr"  "gal"

where f is your list. f是您的列表。

there is not need to iterate like with a for loop 不需要像for循环那样进行迭代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM