lundi 4 décembre 2017

IFELSE for unknown list size R

A - I have a list containing igraph graph objects:

goodgg

[[1]]
IGRAPH UN-- 3 3 -- 
+ attr: name (v/c), color (v/c), value (e/n), sourceID (e/n), targetID (e/n)
+ edges (vertex names):
[1] 89315--89316 89315--89928 89316--89928

[[2]]
IGRAPH UN-- 3 2 -- 
+ attr: name (v/c), color (v/c), value (e/n), sourceID (e/n), targetID (e/n)
+ edges (vertex names):
[1] 106277--106278 106278--106279

I can combine these into a single object using [union][1]:

combine = graph.union(goodgg[[1]], goodgg[[2]], byname=T)

combine
IGRAPH UN-- 6 5 -- 
+ attr: color_1 (v/c), color_2 (v/c), name (v/c)
+ edges (vertex names):

From this, I can extract particular attributes e.g. a color, which lines up with the order of the original objects (1 - 2):

get.vertex.attribute(combine)
$color_1
[1] "red"    "red"    "orange" NA       NA       NA      

$color_2
[1] NA    NA    NA    "red" "red" "red"

$name
[1] "89315"  "89316"  "89928"  "106277" "106278" "106279"

I want to extract the non NA values in $color_1 and $color_2 and merge them into a new list. In this simple case I can do what this answer did here:

V(combine)$color <- ifelse(is.na(get.vertex.attribute(combine)$color_1), get.vertex.attribute(combine)$color_2,get.vertex.attribute(combine)$color_1)

get.vertex.attribute(combine)$color
[1] "red"    "red"    "orange" "red"    "red"    "red" 

However, in reality my list could have n elements. How can I adjust this to account for n elements?

I considered using multiple nested IFELSE statements such as here and here a la:

V(combine)$color <- ifelse(is.na(get.vertex.attribute(combine)$color_1), ifelse(is.na(get.vertex.attribute(combine)$color_2), ifelse(get.vertex.attribute(combine)$color_3)......))

But this looks not good to me and does not solve the issue of having an unknown number n of attributes to work with.

I'm used to Python and a little out of my depth. Any idea how I can achieve this?

Many thanks for your help.

B - A simplified version of the problem is:

I have 2 lists:

a <- get.vertex.attribute(combine)$color_1
b <- get.vertex.attribute(combine)$color_2
> a
[1] "red"    "red"    "orange" NA       NA       NA      
> b
[1] NA    NA    NA    "red" "red" "red"

I want to combine them ignoring NA. I do this by doing:

c <- ifelse(is.na(a), b, a)
> c
[1] "red"    "red"    "orange" "red"    "red"    "red"  

How do I do this when I have n lists (when I don't know n)?

I have included this as it provides a simplified description, however the info in A shows the added complexity in case it is needed.

Aucun commentaire:

Enregistrer un commentaire