Skip to content

How to dynamically add variables to a dataframe

4 messages · Luca Meyer, Eric Berger, Ista Zahn +1 more

#
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
#
Hi Luca,
How about this?

# create some dummy data since I don't have your d0 or d1
# here's the suggested code
HTH,
Eric
On Sun, Apr 22, 2018 at 11:13 AM, Luca Meyer <lucam1968 at gmail.com> wrote:

            

  
  
1 day later
#
Another option is

d0[paste0("V", 1:nrow(d1))] <- 0

--Ista
On Sun, Apr 22, 2018 at 4:23 AM, Eric Berger <ericjberger at gmail.com> wrote:
#
Like this?
Ozone Solar.R Wind Temp Month Day fee fie foe
1    41     190  7.4   67     5   1   0   0   0
2    36     118  8.0   72     5   2   0   0   0
3    12     149 12.6   74     5   3   0   0   0
4    18     313 11.5   62     5   4   0   0   0
5    NA      NA 14.3   56     5   5   0   0   0
6    28      NA 14.9   66     5   6   0   0   0