0

I have a dataframe with 467 columns. When I want to select specific columns

input <- c("bread", "milk")
for (i in 1:length(input)){
    flow <- df[input[i]]}

It return only the "milk" column. Is there any solution to this problem?

nurma_a
  • 139
  • 8
  • Why not just `flow <- df[, c("bread", "milk")]`? Or is there more to that `for` loop? – Maurits Evers Jun 20 '18 at 11:46
  • So I want to build a dataframe, but it joins columns from dataframe “flow” 2 times `for (i in 1:length(input)){ flow <- data_cropped_f[input[i]] menu <- cbind(menu, flow) menu$score <- menu$score+ as.numeric(menu[,input[i]]) }` – nurma_a Jun 20 '18 at 11:51
  • You're *repeatedly* `cbind`ing `menu` in your `for` loop. Is that *really* what you want to do? – Maurits Evers Jun 20 '18 at 11:54
  • I just want to join 2 dataframes based on the `input`. Should I not write it in a loop? – nurma_a Jun 20 '18 at 11:56
  • Joining two dataframes is best done with `merge` (see here: https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right). – LAP Jun 20 '18 at 11:58
  • it also gives the following error `menu$score <- as.numeric(menu$score)+ as.numeric(menu[,input]) Error: (list) object cannot be coerced to type 'double'` – nurma_a Jun 20 '18 at 12:06

0 Answers0