1

I am in the process of reformatting a few data frames and was wondering if there is a more efficient way to add named columns to data frames, rather than the below:

colnames(df) <- c("c1", "c2)

to rename the current columns and:

df$c3 <- ""

to create a new column.

Is there a way to do this in a quicker manner? I'm trying to add dozens of named columns and this seems like an inefficient way of going through the process.

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
Franchise
  • 1,081
  • 3
  • 15
  • 30

3 Answers3

4

use your method in a shorter way:

cols_2_add=c("a","b","c","f")
 df[,cols_2_add]=""
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

A way to add additional columns can be achieved using merge. Apply merge on existing dataframe with the one created with a desired columns and empty rows. This will be helpful if you want to create columns of different types.

For example:

# Existing dataframe
df <- data.frame(x=1:3, y=4:6)

#use merge to create say desired columns as a, b, c, d and e
merge(df, data.frame(a="", b="", c="", d="", e=""))

# Result
#  x y a b c d e
#1 1 4          
#2 2 5          
#3 3 6

# Desired columns of different types
library(dplyr) 
bind_rows(df, data.frame(a=character(), b=numeric(), c=double(), d=integer(),
e=as.Date(character()), stringsAsFactors = FALSE))

#  x y    a  b  c  d    e
#1 1 4 <NA> NA NA NA <NA>
#2 2 5 <NA> NA NA NA <NA>
#3 3 6 <NA> NA NA NA <NA>
MKR
  • 19,739
  • 4
  • 23
  • 33
0

A simple loop can help here

name_list <- c('a1','b1','c1','d1')

# example df
df <- data.frame(a = runif(3))

# this adds a new column
for(i in name_list)
{
    df[[i]] <- runif(3)
}

# output
           a         a1        b1        c1        d1
1 0.09227574 0.08225444 0.4889347 0.2232167 0.8718206
2 0.94361151 0.58554887 0.7095412 0.2886408 0.9803941
3 0.22934864 0.73160433 0.6781607 0.7598064 0.4663031

# in case of data.table, for-set provides faster version:
# example df
df <- data.table(a = runif(3))

for(i in name_list)
    set(df, j=i, value = runif(3))
YOLO
  • 20,181
  • 5
  • 20
  • 40