Kay Kay - 24 days ago 9
R Question

create empty dataframe and error replacement has 1 row, data has 0 occurs

I need to create an empty dataframe, and set up columns for appending values later on.

My code:

df <- data.frame()

varNames <- c("rho", "lambda", "counts")
colnames(df)<- varNames
df['$rho'] <- NA
df["lambda"] <- NA
df["counts"] <- NA


But


Error in [<-.data.frame(*tmp*, "$rho", value = NA) : replacement has 1 row, data has 0



occurs.

Answer Source

We can use

df1 <- data.frame(rho = numeric(), lambda = numeric(), counts = numeric()) 
rbind(df1, list(rho = NA, lambda = NA, counts = NA))
#  rho lambda counts
#1  NA     NA     NA

If we are assigning separately, then a list would be useful

lst <- setNames(vector("list", 3), varNames)
lst[['rho']] <- NA
lst[['lambda']] <- NA
lst
#$rho
#[1] NA

#$lambda
#[1] NA

#$counts
#NULL

as list elements can be of different length whereas a data.frame is a list with equal length columns. Once the assignments are completed and are of equal lengths, then convert it to data.frame with data.frame(lst) and write it back to file