Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get same column by name using same code for two differently structured lists

Tags:

list

r

I have two differently structured lists. And in a function I want to get a column that has the same name in both lists. Is there a generic way to deal with this?

  list_1_1_1 <- list(list(list(tibble::tibble("a" = c(1, 2), "b"=c(3, 4))), list("a"=c(1, 2))))
  list_1_1_1
  # Call column called b
  list_1_1_1[[1]][[1]][[1]]$b

  
  list_1_1 <- list(list(tibble::tibble("a" = c(1, 2), "b"=c(3, 4))), list("a"=c(1, 2)))
  list_1_1
  # Call column called b
  list_1_1[[1]][[1]]$b

I would like to get column called b, with the same line of code that works in the two different situations/examples, is that possible? Thanks in advance.

like image 969
Gorp Avatar asked Jul 07 '20 09:07

Gorp


1 Answers

Maybe something like this.

foo <- function(l, pattern) {
  u <- unlist(l)
  unname(u[grep(pattern, names(u))])
}

foo(list_1_1_1, "b")
# 3 4

foo(list_1_1, "b")
# 3 4
like image 64
jay.sf Avatar answered Nov 05 '22 18:11

jay.sf