1
Edited - As pointed out in Marcos Moraes' comment, I tried to reinvent the wheel of a resource available in the base layer of R, since dput is able to produce the same effect. Fault ours. : ( The central question of my question still remains valid, how to optimize the code below eliminating the structures "for"?
Often when trying to resort to stackoverflow support it is highly recommended that we send example codes and data of the problem we are facing. Sending the code in general does not cause major difficulties, the data does not always. There are cases where generating random sequences and numbers is enough, in others more complex, not. I partially solved this problem with a code that doesn’t adopt compact style and apply family functions.
A data frame as in the example below:
is given to the function and returns a string with the corresponding code:
"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 little 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)
}
Since it would be a "R" -style version, I mean compacting the "for" commands through functions of the "apply" family"?
Is there a specific reason to use a special function instead of the command
dput
, already implemented in all versions of R?– Marcus Nunes
@Marcusnunes I will be frank, I did not know the police :(
– jcarlos
It happens. From what I see on the Internet,
dput
is the most commonly used command to share data, even here at stackoverflow.– Marcus Nunes