Kay Kay - 5 months ago 172
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


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


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
#[1] NA

#[1] NA


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download