-1

I have some data

structure(list(Factor = c(0L, 1L, 0L, 1L, 1L, 0L, 1L), Col_A = c(45L, 
23L, 35L, 43L, 42L, 23L, 11L), Col_B = c(85L, 67L, 55L, 40L, 
27L, 85L, 12L), New_Column = c(45L, 67L, 35L, 40L, 27L, 23L, 
12L)), class = "data.frame", row.names = c(NA, -7L))

Pretend that the 4th column is not there. I need to write a script that based on the value in the Factor column will take a value from either Col_A or Col_B and put in New_Column. If the value in Factor is 0 it should take the value in Col_A so the value in New_Column in the first row is 45.

Jin
  • 527
  • 6
  • 21
  • `df %>% mutate(New_Column = ifelse(Factor==0,Col_A,Col_B))` – maydin Aug 20 '19 at 07:13
  • @maydin tried something like this on real data and received this error `object of type 'closure' is not subsettable` – Jin Aug 20 '19 at 07:20
  • So ,share the just a few part of your real data. You can use `dput(head(data))`. By the input you gave above, this approach works well. – maydin Aug 20 '19 at 07:23
  • I cannot share my data. However, one thing I can add is that there are NA values in this. would that change anything? – Jin Aug 20 '19 at 07:26
  • So I suggest, have a look at the error message, try to solve it wrt the anwers. Because your problem is not about the solution of the problem above. You may start from [here](https://stackoverflow.com/questions/11308367/error-in-my-code-object-of-type-closure-is-not-subsettable) – maydin Aug 20 '19 at 07:29

2 Answers2

0

A base solution:

df$New_Column <- ifelse(df$Factor == 0, df$Col_A, df$Col_B)
s__
  • 9,270
  • 3
  • 27
  • 45
  • I tried something like this on my actual data and received this error ` object of type 'closure' is not subsettable` (before anyone asks, I legally cannot share the real data) – Jin Aug 20 '19 at 07:18
  • The problem is that with your fake data, works well. Can't you creare some fake data that makes your error? Maybe a kind of transformation of your real data. – s__ Aug 20 '19 at 07:25
  • ok interesting thing here. I subset the data taking only the columns of interest and the code works now. But on the whole dataset it doesn't work. So I can splice back in the correct column, but now I'm just curious why it does not work on the same exact data but with other columns included. I'll add there's no difference in structure – Jin Aug 20 '19 at 07:30
  • If you've subset the dataset by columns, try to add one by one the other columns, to fetch the one that create the problem (trying to find a solution of a blackbox). – s__ Aug 20 '19 at 07:32
  • 1
    that sounds like a good call. This dataset's structure is so messed up so that could be it. I'll come back to this once ive written everything up – Jin Aug 20 '19 at 07:34
0

We can use row/column indexing to get the value

df1$New_Column <- df1[2:3][cbind(seq_len(nrow(df1)), df1$Factor + 1)]
akrun
  • 874,273
  • 37
  • 540
  • 662