Finding Elements of Lists in R

后端 未结 3 1199
执念已碎
执念已碎 2020-12-16 01:33

Right now I\'m working with a character vector in R, that i use strsplit to separate word by word. I\'m wondering if there\'s a function that I can use to check the whole li

3条回答
  •  感动是毒
    2020-12-16 02:08

    As alexwhan says, grep is the function to use. However, be careful about using it with a list. It isn't doing what you might think it's doing. For example:

    grep("c", z)
    [1] 1 2 3   # ?
    
    grep(",", z)
    [1] 1 2 3   # ???
    

    What's happening behind the scenes is that grep coerces its 2nd argument to character, using as.character. When applied to a list, what as.character returns is the character representation of that list as obtained by deparsing it. (Modulo an unlist.)

    as.character(z)
    [1] "c(\"a\", \"b\", \"c\")" "c(\"b\", \"d\", \"e\")" "c(\"a\", \"e\", \"f\")"
    
    cat(as.character(z))
    c("a", "b", "c") c("b", "d", "e") c("a", "e", "f")
    

    This is what grep is working on.

    If you want to run grep on a list, a safer method is to use lapply. This returns another list, which you can operate on to extract what you're interested in.

    res <- lapply(z, function(ch) grep("a", ch))
    res
    [[1]]
    [1] 1
    
    [[2]]
    integer(0)
    
    [[3]]
    [1] 1
    
    
    # which vectors contain a search term
    sapply(res, function(x) length(x) > 0)
    [1]  TRUE FALSE  TRUE
    

提交回复
热议问题