dragon
dragon

Reputation: 88

Appending a data frame with for if and else statements or how do put print in dataframe

How do I put what I printed in a dataframe with a for loop and if else statements? Basically, this code:

list<-c("10","20","5")
for (j in 1:3){
  if (list[j] < 8) 
    print("Greater")
  else print("Less")
})
#[1] "Less"
#[1] "Less"
#[1] "Greater"

Or should it be something more like this?

f3 <- function(n){
  df <- data.frame(x = numeric(n), y = character(n), stringsAsFactors = FALSE)
  for(j in 1:3){
    if (list[j] < 8)
    df$x[j] <- j
    df$y[j] <- toString(Greater)
    else
    df$y[j] <- toString(Less)
  }
  df
}

Upvotes: 2

Views: 390

Answers (1)

MrFlick
MrFlick

Reputation: 206232

It's generally not a good idea to try to add rows one-at-a-time to a data.frame. it's better to generate all the column data at once and then throw it into a data.frame. For your specific example, the ifelse() function can help

list<-c(10,20,5)
data.frame(x=list, y=ifelse(list<8, "Greater","Less"))

Upvotes: 2

Related Questions