Function to extract values from list with nonstandard column names

Hello!

I am trying extract values from a list using a for loop, and I am creating a function to pull those values by differing column names (x). The problem is the column names are nonstandard, e.g., they start with an integer. I know that we need to reference nonstandard column names with ``, but I'm having trouble understanding how I could use that in the following function:

getValue <- function(colname){
data[[1]][[2]]$colname
}

However, when I use the function, I get errors or NULL values. This is what I have tried

value <- getValue(`0_D`).

or

getValue <- function(colname) {
data[[1]][[2]]$`colname`
}

But none of those work. I also tried putting {{colname}} in the function but that didn't work either. Anybody have an idea how I can achieve this (besides changing the column names, as this data comes from json files that are not named by me)?

Thanks so much!

I think this does what you want.

TheList <- list(list(list(1:15), list(`1_B` = 1:3, `2_A` = 1:5)))

getValue <- function(colName) {
  TheList[[1]][[2]][[colName]]
}
getValue("1_B")
#> [1] 1 2 3

Created on 2023-10-17 with reprex v2.0.2

1 Like

when you have a level of indirection, and are metaprogramming, you should use [[ ]] syntax rather than $ syntax.

example :

(mylist <- list(
  `a name` = "value"
))


# interactive useage i.e. programmer has typed it out
mylist$`a name`

# adding indirection , a variable contains the the thing to be used
var_to_use <- "a name"

# wont work; $ is for interactive uses and does not support evaluation
mylist$var_to_use

# works 
mylist[[var_to_use]]
1 Like

Thank you so much for that explanation! That was very helpful, and it worked :slight_smile:

Beautiful. It's exactly what I wanted. You are always so helpful and just the best!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.