0

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.

Ollie Perkins
  • 333
  • 1
  • 12

1 Answers1

1

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"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Thanks Ronak - crazy the things you don't know sometimes. I have been using R for a couple of years now and never knew you could index a list using the index name inside bracket indexing. – Ollie Perkins Jul 18 '19 at 10:19