Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

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.

like image 973
Lumos Avatar asked Jun 01 '26 12:06

Lumos


1 Answers

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

like image 191
akrun Avatar answered Jun 04 '26 12:06

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!