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

Time:06-15

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:

$dx
[1] "1234"

$ou
[1] "4567"

$pe
[1] "last_year"

$co
NULL

$ao
NULL

CodePudding user response:

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
  • Related