Assign multiple object and functions in a list by loop or apply family

78 Views Asked by At

I am creating a list that contained multiple objects and functions.
Each object and function had a similar naming and pattern.
Refer below as the example. In the real case, we have lots more assignments.

lst <- list()

lst$ObjectA <- character()
lst$ObjectB <- character()
lst$ObjectC <- logical()

## by object
lst$.setObjectA <- function(A){
  lst$ObjectA <- A
}

lst$.setObjectB <- function(B){
  lst$ObjectB <- B
}

lst$.setObjectC <- function(C){
  lst$ObjectC <- C
}

So I am wondering if can we do this via loop or the apply family, by creating the vector as below.

object <- c("A", "B", "C", "D", "E")
objectClass <- ("character", "character", "logical", "numeric", "character")

But I don't know how to start, as this involved naming the function and creating the actual function, by codes.

Thank you!

1

There are 1 best solutions below

0
Chris On

Yes, (or no), but why...

lst <- list()
object <- c("A", "B", "C", "D", "E")
objectClass <- ("character", "character", "logical", "numeric", "character")

for(k in 1:length(object)) {
 lst[[k]] = object[k]
 names(lst[[k]]) = object[k]
 class(lst[[k]]) = objectClass[k]
 }
Warning message:
In class(lst[[k]]) <- objectClass[k] : NAs introduced by coercion
> lst[[1]]
  A 
"A" 
> str(lst)
List of 5
 $ : Named chr "A"
  ..- attr(*, "names")= chr "A"
 $ : Named chr "B"
  ..- attr(*, "names")= chr "B"
 $ : Named logi NA
  ..- attr(*, "names")= chr "C"
 $ : Named num NA
  ..- attr(*, "names")= chr "D"
 $ : Named chr "E"
  ..- attr(*, "names")= chr "E"

As the warning suggests, there's nothing magical about a 'setting' function as viewed by the compiler that would reasonably view 'C' as logical, nor 'D' numeric. So, it remains, what are you trying to achieve, classes being what they are in R.