I need to set certain numerical values ββin one column of my data frame to zero, if in another column they have a certain level of factor.
My dataframe df looks something like this:
Items Store.Type 5 A 4 B 3 C 6 D 3 B 7 E
I want to make Item = 0, for all lines where Store.Type = "A" or "C"
I am very new to R, but decided it would be a conditional expression of the form βIf Store.Type A then Items <- 0β (and then repeat for Store.Type C), but I didnβt understand the page ?"if" at all . I tried:
df$ItemsFIXED <- with(df, if(Store.Type == "A")Items <-0)
and received a warning message:
Warning message: In if (Store.Type2 == "Chain - Brand") Total.generic.items <- 0 : the condition has length > 1 and only the first element will be used`
So, I noticed here , the following:
if is a control flow statement that takes one boolean as an argumentifelse is a vectorized function that takes vectors as all its arguments.
So, assuming that I need ifelse to make the whole column and understand the page ?ifelse , I tried to do "If Store.Type A, then Items <- 0 else do nothing." Actually, I wanted it to be nested, so I tried the following code (now I create a new column so as not to spoil my data, but in the end it will overwrite the Items data)
df$ItemsFIXED <- with(df, ifelse(Store.Type == "A", Items <-0, ifelse(Store.Type == "C", Items <-0,)))
and got the following error:
Error in ifelse(Store.Type2 == "Franchise - Brand", Total.generic.items <- 0, : argument "no" is missing, with no default
But if I put something for no , it just writes over the correct values. I tried putting Items and Items <- Items in to say "else leave Items as Items", as in the following, but it just changed everything to zero.
df$ItemsFIXED <- with(df, ifelse(Store.Type == "A", Items <-0, ifelse(Store.Type == "C", Items <-0,Items)))
Is there a way to tell ifelse do nothing or is there an easier way to do this?