0

I'm trying to create a loop where if x is below a certain value, one dataframe is produced, and if it is above a certain value, a different one is produced, within an ifelse statement. Here is some dummy data approximating what I'm trying to do:

population <- sample(c(1000:9999), 10)
year <- sample(c(2009:2020), 10)

for(x in 1:10){
  df <- ifelse(x < 5, as.data.frame(population), as.data.frame(year))
  print(head(df))
}

However, the df that is produced just ends up being a list instead of a matrix of observations and variables. Is there a way to fix this?

tchoup
  • 971
  • 4
  • 11
  • Based on this example, are you just trying to split the data frames by row number? Rows 1:4 in one data frame and 5:10 in the other? If so, you could simply do `data.frame(population, year)[1:5,]`. – LMc Mar 23 '23 at 14:17
  • If you use 2 `if`, the code works – Yacine Hajji Mar 23 '23 at 14:20
  • 1
    `ifelse` has to return something the same "shape" as the test case - if your test `x < 5` is a vector of length 10, then the result will be a vector of length 10. You're trying to using it on a vector of length 1 to return a data frame - that won't work. You can use `if(){}else{}` for things like that. – Gregor Thomas Mar 23 '23 at 14:21
  • 3
    ...but that's not your only problem. Your loop overwrites `df` every iteration, without saving the early iterations anywhere. It's not at all clear what your final result is supposed to be... do you want a a `list` of replicates of your data? Everything combined in one big data frame? Something else? – Gregor Thomas Mar 23 '23 at 14:23
  • Thanks ya'll - the if(){}else{} solution worked. Also, I know I can split it, and I know that it overwrites the df every time. The actual data and code does not do that, but I can't share that publicly and the only piece I needed figured out was how to have an ifthen statement produce dataframes. – tchoup Mar 28 '23 at 14:52

1 Answers1

0

From @GregorThomas - the if(){}else{} code worked:

for(x in 1:10){
  df <- if(x < 5){as.data.frame(population)}else{as.data.frame(year)}
  print(head(df))
}
tchoup
  • 971
  • 4
  • 11