0

I have a data frame with questions A, B, C, and D. I need to create a new variable that returns "Red" (or 1, whichever is easier) when:

A=1 & B=3 & C=1 & D=1 

I'm not having any luck getting any functions or code I've searched to work thus far so any help is appreciated.

I've tried case_when and a few other functions

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
  • 3
    You could use a [`case_when`](https://dplyr.tidyverse.org/reference/case_when.html) function from the `dplyr` package to vectorise multiple statements. – Quinten Aug 11 '23 at 16:36
  • 2
    `dat$newvar <- ifelse(with(dat, A==1 & B==3 & C==1 & D==1), "Red", "something else")` ? – r2evans Aug 11 '23 at 16:42
  • 2
    Welcome to SO, Val Siegel! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including attempted code (please be explicit about non-base packages), sample representative data (perhaps via `dput(head(x))` or building data programmatically (e.g., `data.frame(...)`), possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Aug 11 '23 at 16:43
  • 1
    Can you post sample data? Please edit the question with the output of `dput(df)`. Or, if it is too big with the output of `dput(head(df, 20))`. – Rui Barradas Aug 11 '23 at 16:43

2 Answers2

0
df <- df %>% 
  mutate(newcolumn = 
           case_when(a==1 & b == 3 & x==3 & d==3 ~'red',
                     a==2 & b == 3 & x==8 & d==3 ~'blue',
                     TRUE ~ 'next'))

Case when is my favorite function for this kind of categorizations. It's incredibly flexible. Post your code if this doesn't work for you.

JSP
  • 35
  • 5
  • Thanks for the help! I'm now using: df <- df %>% mutate(newcol = case_when(a == 1 & b == 3 & x == 1 & d == 1 ~ 'Red', TRUE ~ '0')) This has made the variable for me without technical errors, but unfortunately I'm still not getting any cases of "Red", though I know there should be some. Thoughts? – Val Siegel Aug 14 '23 at 18:14
0

just use logical indexing

idx <- df$A ==1 & df$B ==3 & df$C ==1 & df$D == 1
df$newcol <- NA
df$newcol[idx] <- "RED"
Drj
  • 1,176
  • 1
  • 11
  • 26