R add column to 0-row df

Viewed 132

In R, how to add a column to a zero-row data.frame?

I can't do df[,'newcol'] <- NULL or c() because these statements actually drop existing columns.

df <- data.frame(col1=c(1:3), col2=letters[1:3])
df <- df[-c(1:3),]
df[,'newcol'] <- NULL
3 Answers

If you know the column type, you could add an empty column type:

df$newcol <- numeric(0)
df

[1] col1   col2   newcol
<0 rows> 

Another possible solution:

df <- data.frame(col1=c(1:3), col2=letters[1:3])
df <- df[-c(1:3),]

df <- cbind(df, new_col=df[,1])
df

#> [1] col1    col2    new_col
#> <0 rows> (or 0-length row.names)

A possible dplyr solution:

library(dplyr)

df %>% 
  bind_cols(new_col=length(df))

# [1] col1    col2    new_col
# <0 rows> (or 0-length row.names)

Or we could also use the class as @Waldi did:

df %>% 
  bind_cols(new_col=numeric(0))
Related