Search code examples
rlistelementnamed

How to get a named list element in R if the appearance of the element is conditional?


I want to include a list element c in a list L in R and name it C. The example is as follows:

a=c(1,2,3)
b=c("a","b","c")
c=rnorm(3)
L<-list(A=a,
        B=b,
        C=c)
print(L)

## $A
## [1] 1 2 3
## 
## $B
## [1] "a" "b" "c"
## 
## $C
## [1] -2.2398424  0.9561929 -0.6172520

Now I want to introduce a condition on C, so it is only included in the list if C.bool==T:

C.bool<-T
L<-list(A=a,
        B=b,
        if(C.bool) C=c)

print(L)

## $A
## [1] 1 2 3
## 
## $B
## [1] "a" "b" "c"
## 
## [[3]]
## [1] -2.2398424  0.9561929 -0.6172520

Now, however, the list element of c is not being named as specified in the list statement. What's the trick here?

Edit: The intention is to only include the element in the list if the condition is met (no NULL shoul be included otherwise). Can this be done within the core definition of the list?


Solution

  • I don't know why you want to do it "without adding C outside the core definition of the list?" but if you're content with two lists in a single c then:

    L <- c(list(A=a, B=b), if(C.bool) list(C=c))
    

    If you really want one list but don't mind subsetting after creation then

    L <- list(A=a, B=b, C=if(C.bool) c)[c(TRUE, TRUE, C.bool)]
    

    (pace David Arenburg, isTRUE() omitted for brevity)