0

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!

Howard
  • 61
  • 4
  • Hi, whats the desired outcome for the provided example? Additionally, are you sure the third instance in the object vector should be a character if you want the class to be logical? – fabla Apr 13 '23 at 09:15
  • I find this very confusing. What would be the purpose for this? If object A and class is character, you can just define A as charcter `A = character(0)` ? – Mislav Sagovac Apr 13 '23 at 09:24
  • Hello, the desired outcome is the `lst` with objects `ObjectA, ObjectB, ObjectC, ...` and functions `.setobjectA, .setObjectB, .setObjectC, ...` Yes, we could do that, but could we assign them by batch instead of entering them lines by lines? – Howard Apr 13 '23 at 12:25

1 Answers1

0

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.

Chris
  • 1,647
  • 1
  • 18
  • 25