Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a data.frame with a given name from a function?

Tags:

r

lapply

Assume I have a function that reads data from a MySQL table, manipulates it and returns some data.frame. Note the function is just an example whose functionality does not matter itself..., E.g.:

addRowSd <- function(table,con,pattern="^Variable") {

dframe <- dbReadTable(con,table)
cn <- colnames(dframe)
qs <- subset(x, x  %in% grep(pattern, x, value=TRUE))
dframe$qsd <- sd(t(dframe[,c(qs)])) 

return(dframe)
}

mydf$sd <- addRowSd(...)

I end up with a data.frame called mydf. Now I´d like to do to this to a character vector of SQL table names AND name the returned dataframes correspondingly. If I just use

x=lapply(MySQLtablenames,addRowSd,con)

I´ll get some list called x. Of course I could unlist and rename everything the way I´d like to, but my question is:

How can I make lapply (or another comparable function) return multple single dataframes or at least a list that contains some names derived from my character vector "MySQLtablenames"?

like image 330
Matt Bannert Avatar asked Oct 28 '10 10:10

Matt Bannert


People also ask

How do I get the Dataframe name in R?

If you've got more than one dataframe that you want to retrieve the name of, you can use ls. str(mode = "list") . We use list because dataframes are stored as lists. Note that this method will also include the names of other list objects in your global environment.

What does the data frame () function do?

The function data. frame() creates data frames, tightly coupled collections of variables which share many of the properties of matrices and of lists, used as the fundamental data structure by most of R's modeling software.

How do you create a data frame with two variables?

How to Create a Data Frame. We can create a dataframe in R by passing the variable a,b,c,d into the data. frame() function. We can R create dataframe and name the columns with name() and simply specify the name of the variables.

What is as data frame () in R?

A data frame is a two-dimensional data structure which can store data in tabular format. Data frames have rows and columns and each column can be a different vector. And different vectors can be of different data types.


2 Answers

just found an answer on my own:

assign("somename",dframe,envir = .GlobalEnv)
like image 106
Matt Bannert Avatar answered Sep 20 '22 22:09

Matt Bannert


If you supply sapply a character vector, it will name the items in the returned list by the supplied character vector (USE.NAMES default to TRUE)... I would also use simplify=FALSE as depending on the data.frames returned you may get unpredictable results

x=sapply(MySQLtablenames,addRowSd,con, simplify=FALSE)
like image 32
Aaron Statham Avatar answered Sep 24 '22 22:09

Aaron Statham