简体   繁体   中英

Subset my R list by character vector from dataframe

I have an r object, 'd' that is a list. I want a dataframe of references to subsets of this list to make as variables for a function, 'myfunction'. This function will be called thousands of times using rslurm each using a different subset of d.

example: d[['1']][[3]] references a data matrix within the list.

myfunction(d[['1']][[3]]) 

works fine, but I want to be able to call these subsets from a dataframe.

I want to be able to have a dataframe, 'ds' containing all of my subset references.

>ds
              d
1 d[['1']][[3]]
2 d[['1']][[4]]

>myfunction(get(ds[1,1]))
Error in get(ds[1, 1]) : object 'd[['1']][[3]]' not found

Is there something like 'get' that will let me call a subset of my object, d? Or something I can put in 'myfunction' that will clarify that this string references a subset of d?

stack_overflow 'get'

A list :

my_list <- c('peanut', 'butter', 'is', 'amazing')

A dataframe containing subset references :

my_dataframe <- data.frame(keys=c("my_list[[1]]", "my_list[[2]]", "my_list[[3]]", "my_list[[4]]"), stringsAsFactors=F)

在此处输入图片说明

A function that extracts the value from a list based on a passed value:

my_function <- function(key, my_list) {
    from_list <- eval(parse(text=key))
    print(from_list)
}

Getting the value from a list by passing in the dataframe row choice and the list:

my_function(my_dataframe[1,1], my_list)

在此处输入图片说明

I solved this by changing myfunction to take two variables, c and w, and defining d using bracket notation in the first line of the updated function. My ds now has two variables, c and w, with variable c defined as as.character and it works!

myfunction(c,w) {
d<-d[[c]][[w]]
....rest of function}

>ds
 c w
1 1 3
2 1 4

>test <- myfunction(ds[1,1],ds[1,2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM