简体   繁体   中英

Selecting a data frame from a list of data frames as an argument in a function in R

Hey I'd like to use a data.frame from a large list as an argument in a function. My data has a list of NBA team data where each team is a data.frame in the list ; for the function I made to be most effective, I would need to use the team as an argument. Here is some test data:

a<- data.frame(1,1:10)
b<- data.frame("a",4,"d", 20:25)

c<- list(a,b)
names(c)<- c("a","b")

test<- function(df){
  poop<- subset(c$df, c$df$X1.10==1)
  return(poop)
}

In this example I would want to run something like

test("a")

but I'm struggling to get it. Any ideas would be greatly appreciated

See if this is what you wanted. I did some rewriting. First, for the function to return a data frame in the global environment, you should use "<<". If not, you can keep "<-". But remember that as a local variable, the data frame will exist only when the function is running.This is similar to the global assignment of a variable in Python. Second, there is a better way to subset the data frame as I show below:

a<- data.frame(1,1:10)
b<- data.frame("a",4,"d", 20:25)

c<- list(a,b)
names(c)<- c("a","b")

test<- function(df){
    poop<<- subset(df, df$X1.10==1)
    return(poop)
}

test(c[[1]])

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