bird
bird

Reputation: 3294

How to name columns based on the number of iteration in a loop (in R)?

I want to make names based on the number of iterations in an R loop. For example, I want my columns in the data frame to be called "column_1", "column_2" and so on. So far, I have tried the following code, but it does not work:

df = data.frame(rep(0, 5))
for (i in 1:5) {
        
        df = cbind(df, paste0("column_", i) = rnorm(5))
        
}

Also, please note that if it did work, I would need to remove the first column using:

df = df[,-1]

What is the best way to avoid creating such an initial column? I created it because an empty data frame df = data.frame() does not take a new column when using df = cbind(df, rnorm(5)) because of the mismatch between the number of rows.

Upvotes: 0

Views: 942

Answers (2)

Gi_F.
Gi_F.

Reputation: 961

Try like this

df = list()
for (i in 1:5) {
        
    df[[paste0("column_", i)]] =  rnorm(5)
        
}

do.call('data.frame', df)
     column_1   column_2   column_3   column_4    column_5
1 -0.47624689  0.1192452  1.6756969 -0.5739735  0.05974994
2 -0.78860284  0.2436874 -0.4411632  0.6179858 -0.70459646
3 -0.59461727  1.2324759 -0.7230660  1.1098481 -0.71721816
4  1.65090747 -0.5160638 -1.2362731  0.7075884  0.88465050
5 -0.05402813 -0.9925072 -1.2847157 -0.3636573 -1.01559258

Alternatively, in order to pre-allocate df, I might try also this

df        = vector('list', 5)
names(df) = paste0("column_", 1:5)
for(i in 1:5) df[[i]] = rnorm(5)
do.call('data.frame', df)

Upvotes: 2

MGP
MGP

Reputation: 2551

Alternativ to the existing solution, you can allocate the appropiate number of rows beforehand using:

len <- 5
df <- data.frame(numeric(len))

for (i in 1:10){
  df[paste0("column_",i)] <- rnorm(len)
}

df[[1]] <- NULL
df

Upvotes: 0

Related Questions