Kush Patel
Kush Patel

Reputation: 3855

How to add value to column when data frame is empty in r

I have data frame that I have to initialized as empty data frame. Now I have only column available, I want to add it to empty data frame. How I can do it? I will not sure what will be length of column in advance.

Example

df = data.frame(a= NA, b = NA, col1= NA)
....
nrow(col1) # Here I will know length of column, and I only have one column available here.
df$col1 <- col1

error is as follows:

Error in `$<-.data.frame`(`*tmp*`, "a", value = c("1",  : 

replacement has 5 rows, data has 1

Any help will be greatful

Upvotes: 2

Views: 9260

Answers (3)

Kush Patel
Kush Patel

Reputation: 3855

I like both answers provided by Symbolix and maRtin, I have done my own hack. My hack is as follow.

df[1:length(a),"a"] = a

However, I am not sure, which one this method is efficient in term of time. What will be big O notion for time

Upvotes: 0

maRtin
maRtin

Reputation: 6516

A little workaround with lists:

l      <- list(a=NA, b=NA, col1=NA)
col1   <- c(1,2,3)
l$col1 <- col1
df     <- as.data.frame(l)

Upvotes: 2

SymbolixAU
SymbolixAU

Reputation: 26248

use cbind

df = data.frame(a= NA, b = NA)

col1 <- c(1,2,3,4,5)
df <- cbind(df, col1)

#    a  b col1
# 1 NA NA    1
# 2 NA NA    2
# 3 NA NA    3
# 4 NA NA    4
# 5 NA NA    5

After your edits, you can still use cbind, but you'll need to drop the existing column first (or handle the duplicate columns after the cbind)

cbind(df[, 1:2], col1)

## or if you don't know the column indeces
## cbind(df[, !names(df) %in% c("col1")], col1)

Upvotes: 4

Related Questions