Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: ignoring an error in a for loop when assigning a value to a list

I am looking to run a for loop on some data looking for certain id codes and then modifying an existing list. I am running into an issue where my list seems to be over written with NULL values; I am sure this is a very simple fix that i can’t wrap my brain around. Below is the code:

# my sample data
    sample_data <- 
  data.frame(
    type = c("dimension", "dimension", "dimension", "dimension", "dimension"),
    d_id = c("1234", "last_year", "4567", "897", "9001"),
    sub_id = c("dx", "pe", "ou", "ytu", "iouy")
  )

# my initial list
my_list <- list(dx = NULL, ou = NULL, pe = NULL, co = NULL, ao = NULL)

# loop, when there is a value assign it within the list, when an error kicks because there is no value assign null
# or could simply leave null
for (dim in c("dx", "ou", "pe", "co", "ao")) {
  
  tryCatch(
    {
      my_list[dim] <- sample_data[sample_data$sub_id == dim & sample_data$type == "dimension",]$d_id
    },
    error = function(e) {
      my_list[dim] <- NULL
    }
  )
  
  
}

What I get:

$dx
NULL

$ou
NULL

$pe
NULL

$co
NULL

$ao
NULL

What I expect:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$dx
[1] "1234"

$ou
[1] "4567"

$pe
[1] "last_year"

$co
NULL

$ao
NULL

>Solution :

This doesn’t need a loop. Just extract the column and use that to assign the d_id to the appropriate names of the list from sub_id

sample_data_sub <- subset(sample_data, sub_id %in% names(my_list))
my_list[sample_data_sub$sub_id] <- sample_data_sub$d_id

-output

> my_list
$dx
[1] "1234"

$ou
[1] "4567"

$pe
[1] "last_year"

$co
NULL

$ao
NULL
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading