[R] Dataframes and assign
    Douglas Bates 
    bates at stat.wisc.edu
       
    Wed Oct  2 19:19:45 CEST 2002
    
    
  
Göran Broström <gb at stat.umu.se> writes:
> I have the following function:
> 
> putsoc <- function(age, dat){
>   ## age is an integer
>   ## dat is a data.frame
> 
>   new.name <- paste("soc", as.character(age), sep = ".")
>   if (new.name %in% names(dat)) stop(paste(new.name, "already in place"))
> 
>   dat$new.var <- rep(1, nrow(dat)) ## Just nonsense.
> 
>   n.var <- ncol(dat)
>   names(dat)[ncol(dat)] <- new.name
>   return(dat)
> }
The $ operator is 'syntactic sugar' that allows you to write
frm$colname instead of frm[['colname']].  In your case you are
generating the name as a character string so you should use the second
form.  That is, write your function as
putsoc <- function(age, dat) {
   new.name <- paste("soc", as.character(age), sep = ".")
   if (new.name %in% names(dat)) stop(paste(new.name, "already in place"))
 
   dat[[new.var]] <- rep(1, nrow(dat))
   return(dat)
}
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
    
    
More information about the R-help
mailing list