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.
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
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