frandude
frandude

Reputation: 89

Return a value from vectors in a list using only column names

Consider the following list. This list (named "list1" in this example) contains three named vectors "A", "B", and "C". Each of those vectors have two columns, which are always named "one" and "two":

> list1
$A
     one      two 
2005.015 1339.938 

$B
      one       two 
1.0000075 0.1815634 

$C
          one           two 
-66264.148352     -2.868802 

Say I want to get the value of the column "two" from the vector "B". There are three ways I know how to do this:

list1[[2]][[2]]
list1$B[[2]]
list1[[2]]$two

However this is not a way to get that value:

list1$B$two

Is there any way to get this value using only the column names, rather than column indexes?

Upvotes: 1

Views: 338

Answers (2)

jpdugo17
jpdugo17

Reputation: 7106

We can convert the vectors inside the list to either a data.frame or a list.

lst <- list(A = c(one = 2005.015, two = 1339.938),
            B = c(one = 1.0000075, two = 0.1815634),
            C = c(one = -66264.148352 , two = -2.868802))

lst <- lapply(lst, function(.x) data.frame(A = .x[[1]], B = .x[[2]]))

lst$A$A
#> [1] 2005.015
lst$B$A
#> [1] 1.000007

lst <- lapply(lst, function(.x) list(A = .x[[1]], B = .x[[2]]))

lst$A$A
#> [1] 2005.015

Created on 2021-07-01 by the reprex package (v2.0.0)

Upvotes: 0

r2evans
r2evans

Reputation: 160407

Those do not appear to be nested frames, nor frames at all: it appears to be a list of named numeric vectors. Here's what I suspect the data is:

nested_df <- list(A=c(one=1,two=2), B=c(one=11,two=12), C=c(one=21,two=22))
nested_df
# $A
# one two 
#   1   2 
# $B
# one two 
#  11  12 
# $C
# one two 
#  21  22 

As such, you can use

nested_df$B["two"]
# two 
#  12 

Raw data:

nested_df <- list(A = c(one = 1, two = 2), B = c(one = 11, two = 12), C = c(one = 21, two = 22))

Upvotes: 0

Related Questions