Search code examples
rlistindexingbnlearn

Convert string to names list index


I have a list with named objects that I would like to assign to by extracting the list index name from a character string. Using the below method I get the following error message: Error: attempt to apply non-function.

Thus:

test <- list(a = 'a', b = 'b', c = 'c')

### works fine

test$a <- 'foo'

### What I would like to be able to do

n <- names(test)[1]

test$parse(text = n) <- 'foo'

PS: This is to assign custom coefficients to a bn.fit object node using the Bnlearn library. For some reason, you can assign using the list index name, but not the list index integer. If there is another workaround that could work in that context, I am all ears.


Solution

  • In that case, don't use $ to subset, use [

    test <- list(a = 'a', b = 'b', c = 'c')
    test[n]$a <- "foo"
    
    test
    #$a
    #[1] "foo"
    
    #$b
    #[1] "b"
    
    #$c
    #[1] "c"
    

    OR [[

    test[[n]] <- "foo"