0

I have an igraph object, what I have created with the igraph library. This object is a list. Some of the components of this list have a length of 2. I would like to remove all of these ones.

IGRAPH clustering walktrap, groups: 114, mod: 0.79
+ groups:
  $`1`
     [1] "OTU0041"             "OTU0016"             "OTU0062"            
     [4] "OTU1362"             "UniRef90_A0A075FHQ0" "UniRef90_A0A075FSE2"
     [7] "UniRef90_A0A075FTT8" "UniRef90_A0A075FYU2" "UniRef90_A0A075G543"
    [10] "UniRef90_A0A075G6B2" "UniRef90_A0A075GIL8" "UniRef90_A0A075GR85"
    [13] "UniRef90_A0A075H910" "UniRef90_A0A075HTF5" "UniRef90_A0A075IFG0"
    [16] "UniRef90_A0A0C1R539" "UniRef90_A0A0C1R6X4" "UniRef90_A0A0C1R985"
    [19] "UniRef90_A0A0C1RCN7" "UniRef90_A0A0C1RE67" "UniRef90_A0A0C1RFI5"
    [22] "UniRef90_A0A0C1RFN8" "UniRef90_A0A0C1RGE0" "UniRef90_A0A0C1RGX0"
    [25] "UniRef90_A0A0C1RHM1" "UniRef90_A0A0C1RHR5" "UniRef90_A0A0C1RHZ4"
  + ... omitted several groups/vertices

For example, this one :

> a[[91]]
[1] "OTU0099"                "UniRef90_UPI0005B28A7E"

I tried this but it does not work :

a[lapply(a,length)>2]

Any help?

Paillou
  • 779
  • 7
  • 16
  • 7
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. What "length" are you referring to here exactly? This seems more specific to `igraph` than just lists in general in R. – MrFlick Jun 14 '19 at 14:37
  • 2
    According to this [reproducible example](https://rextester.com/OKGWH25935), your code should work. See demo's before and after. All items of length 1 and 2 are removed, reducing list of 10 to list of 7. – Parfait Jun 14 '19 at 14:48
  • I am guessing `is.list(a)` evaluates to FALSE. I could be wrong, though. I do not know enough about `igraph` objects. But, if it is a list, your code could be a little cleaner/faster by using `lengths()`: i.e., `a[lengths(a) > 2]`. – Andrew Jun 14 '19 at 15:09

1 Answers1

3

Since you didn't provide any reproducible data or example, I had to produce some dummy data:

# create dummy data
a <- list(x = 1, y = 1:4, z = 1:2)

# remove elements in list with lengths greater than 2:
a[which(lapply(a, length) > 2)] <- NULL

In case you wanted to remove the items with lengths exactly equal to 2 (question is unclear), then last line should be replaced by:

a[which(lapply(a, length) == 2)] <- NULL
PavoDive
  • 6,322
  • 2
  • 29
  • 55