[R] How to dynamically add variables to a dataframe

Eric Berger er|cjberger @end|ng |rom gm@||@com
Sun Apr 22 10:23:59 CEST 2018


Hi Luca,
How about this?

# create some dummy data since I don't have your d0 or d1
> n  <- 3
> d0 <- data.frame(a=runif(5),b=runif(5))

# here's the suggested code
> d1 <- cbind(d0, matrix(0,nrow(d0),n))
> colnames(d1)[1:n + ncol(d0)] <- paste("V",1:n,sep="")

HTH,
Eric


On Sun, Apr 22, 2018 at 11:13 AM, Luca Meyer <lucam1968 using gmail.com> wrote:

> Hi,
>
> I am a bit rusty with R programming and do not seem to find a solution to
> add a number of variables to my existing dataframe. Basically I need to add
> n=dim(d1)[1] variables to my d0 dataframe and I would like them to be named
> V1, V2, V3, ... , V[dim(d1)[1])
>
> When running the following code:
>
> for (t in 1:dim(d1)[1]){
>   d0$V[t] <- 0
> }
>
> all I get is a V variable populated with zeros...
>
> I am sure there is a fairly straightforward code to accomplish what I need,
> any suggestion?
>
> Thank you,
>
> Luca
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]




More information about the R-help mailing list