Reputation: 37
I have a dataframe and I try to keep some values of it into a loop using a code like:
dfnew<- rbind(dfnew, data.frame(var1new= df$var1,
var2new = df$var2))
Sometimes the var1 or var2 doesn't exist into the df and the problem is that there is a error as the df has not the same column length as the dfnew and the loop stops to execute.
Is there any simple way to insert NA if the value doesn't exist? Aimining not to check previously the values with many lines of code. Something like this
dfnew<- rbind(dfnew, data.frame(var1new= df$var1 || NA,
var2new = df$var2|| NA))
Upvotes: 0
Views: 1415
Reputation: 2324
Use if statement:
dfnew<- rbind(dfnew, data.frame(var1new= ifelse(is.null(df$var1),NA,df$var1) ,
var2new = ifelse(is.null(df$var2),NA,df$var2)))
Upvotes: 3