Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data to empty r data.frame

Tags:

dataframe

r

In R, If I make a data.frame with one column, I can added others

> data <- data.frame(n=c(1:4))
> data
  n
1 1
2 2
3 3
4 4
> data$n2 <- 2
> data
  n n2
1 1  2
2 2  2
3 3  2
4 4  2

but, If I make a empty data.frame, I can't add new columns

> data <- data.frame()
> data
data frame with 0 columns and 0 rows
> data$n2 <- 2
Error in `$<-.data.frame`(`*tmp*`, "n2", value = 2) : 
  replacement has 1 row, data has 0

why ? how I can add new columns to empty data.frame ?

like image 850
JuanPablo Avatar asked Feb 27 '26 06:02

JuanPablo


1 Answers

You can add a column to an empty data.frame, but to match the existing data.frame's dimensions, the assigned vector needs to have length zero:

data <- data.frame()
data$n2 <- numeric()
data
# [1] n2
# <0 rows> (or 0-length row.names)

(In your first example, although the value on the RHS of the assignment didn't have the same length as the existing columns, it was "recycled" to form a column of the necessary length. When the existing data.frame has no rows, though, recycling can't be used to make the column lengths match.)

like image 190
Josh O'Brien Avatar answered Mar 01 '26 01:03

Josh O'Brien