Home > Blockchain >  R add column to 0-row df
R add column to 0-row df

Time:01-28

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

CodePudding user response:

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

df$newcol <- numeric(0)
df

[1] col1   col2   newcol
<0 rows> 

CodePudding user response:

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)
  •  Tags:  
  • Related