CodexBloom - Programming Q&A Platform

scenarios when using `purrr::map()` with a list of custom objects in R - how to access attributes

👀 Views: 100 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
r purrr s3 s4 custom-classes R

I'm trying to implement I can't seem to get Quick question that's been bugging me - I'm trying to use `purrr::map()` to apply a function to a list of custom objects in R, but I'm working with an behavior when I try to access the attributes of those objects... I'm using R version 4.1.1 and the `purrr` package version 0.3.4. I have a list of custom objects created from a class `MyClass` which has an attribute `value`. When I attempt to extract the `value` attribute using `map()`, I get the following behavior: ``` behavior in value[[1]] : subscript out of bounds ``` Here's a simplified version of my code: ```r library(purrr) MyClass <- setRefClass( "MyClass", fields = list(value = "numeric") ) obj1 <- MyClass$value(10) obj2 <- MyClass$value(20) my_list <- list(obj1, obj2) result <- map(my_list, ~ .x$value) ``` I've tried checking the contents of `my_list` and they seem to be populated correctly. However, when I run the `map()` function, it throws the aforementioned behavior, indicating that it's unable to find the `value` attribute. I also experimented with using `lapply()` instead, but I encountered a similar scenario. Is there a specific way I need to access attributes of custom class objects when using `purrr::map()`? Any insights would be appreciated! I'm working on a service that needs to handle this. Thanks in advance! I've been using R for about a year now. Cheers for any assistance! Any suggestions would be helpful. For reference, this is a production REST API. Any ideas how to fix this?