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 ?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With