How to send data frames data in code questions in optimized R?

1

Edited - As pointed out in Marcos Moraes' comment, I tried to reinvent the wheel of an available resource in the base layer of R, since dput is capable of producing the same effect. Our failure. :( The central question of my question still remains valid, how to optimize the code below by eliminating the "for" structures?

Often when trying to use support in stackoverflow it is highly recommended that we send sample code and problem data that we are facing. Sending the code in general does not entail greater difficulties, the data is not always. There are cases where the generation of sequences and random numbers is enough, in other more complex, no. I partially solved this problem with a code that does not adopt the compact style and apply family functions.

A data frame like the example below:

issuppliedtothefunctionandreturnsastringwiththecorrespondingcode:

"df <- data.frame(LONG=c(-37.04821264,-48.48782569,-43.92645317,-60.67053267),LAT=c(-10.9072158,-1.459845,-19.93752429,2.816681919),ALT=c(4.288342,8.471477,937.528005,79.828228),name=c('city1','city2','city3','city4'))"

So in a single file I can send the code and the data.

The small function I've developed:

#' dfCode
#' generate a string corresponding to the code
#' of a data frame definition in R
#' 
#' @param df a data frame
#'
#' @return a string with the representation of the data frame
#'         to be used as code in R scripts
#' @export
#'
#' @examples dfCode(df) 
dfCode <- function(df) {

  if(!is.data.frame(df))
  {return(-1)}

  ncols <- ncol(df)
  nrows <- nrow(df)

  k <- "df <- data.frame(" 

  for (j in 1:ncols)
  {
    # open column vector
    k <- paste0(k,colnames(df)[j],"=c(")

    # numeric or not
    for (i in 1:ncols)
    {
      if (is.numeric(df[,j]))
            k <- paste0(k,df[i,j])
      else 
            k <- paste0(k,"'", df[i,j],"'")

      if(i< nrows) # last item no commas
        { k=paste0(k,",")}
    }
    # closing parenthesis vector declaration
    k <- paste0(k,")")

    if(j< ncols)  #last item no commas
    { k=paste0(k,",")}
  }
  k <- paste0(k,")")

  return(k)
}

As an "R" style version, I mean by compressing the "for" commands through "apply" family functions?

    
asked by anonymous 29.10.2016 / 13:43

1 answer

0

One proposal:

dfCode2 <- function(df) {

  if(!is.data.frame(df))
  {return(-1)}

  k <- "df <- data.frame(" 

  tcs=sapply(colnames(df),function(co) {
    tc=df[,co]
    # open column vector
    ks <- paste0(co,"=c(")

    # numeric or not
      if (is.numeric(tc))
        ks <- paste0(ks,paste0(tc,collapse=","),")")
      else 
        ks <- paste0(ks,"'",paste0(tc,collapse = "','"),"')")
  })
  k <- paste0(k,paste0(tcs,collapse=","),")")

  return(k)
}
    
02.11.2016 / 00:54