[R] Dataframes and assign
Göran Broström
gb at stat.umu.se
Wed Oct 2 22:04:32 CEST 2002
Douglas,
this was exactly what I needed! And new to me.
Thanks,
Göran
On 2 Oct 2002, Douglas Bates wrote:
> 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)
> }
>
---
Göran Broström tel: +46 90 786 5223
Department of Statistics fax: +46 90 786 6614
Umeå University http://www.stat.umu.se/egna/gb/
SE-90187 Umeå, Sweden e-mail: gb at stat.umu.se
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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