I have a data frame with multiples dates and associated data/variables. I'm looking to create a new column in the data frame that assigns a Yes or No variable to the new column depending on the date of the other column. For example, all dates before, say, Date1 need a 'Yes' in the new column, and all dates after Date1 need a 'No' in the new column. How do I do this?
Asked
Active
Viewed 273 times
0
-
3Welcome to SO, Julia McDonough! Please make this question *reproducible*. This includes sample code you've attempted (including listing non-base R packages, and any errors/warnings received), sample *unambiguous* data (e.g., `data.frame(x=...,y=...)` or the output from `dput(head(x))`), and intended output given that input. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Oct 25 '21 at 17:43
-
3But another thought: there are literally dozens of questions asked *each week* that ask almost the same title/question. Please search around SO for similar questions. It will likely be a much better solution for you: (1) you can see many already-written solutions to similar problems without waiting for us to see, attempt, and answer; and more important (2) we don't have your data and you've provided no attempted effort or code, so the chance of somebody guessing is really low. Please read the links I provided above, they can be quite helpful, helping you to get better answers, faster. Thanks! – r2evans Oct 25 '21 at 17:45
-
3Does this answer your question? [Can dplyr package be used for conditional mutating?](https://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating) – Karl Oct 25 '21 at 17:49
1 Answers
0
The simplest way to add a new column based on a binary test is with the base R ifelse function. Here's an example using mtcars and testing for mpg >= 25 with the new columns test and test2 added to the dataframe. test2 illustrates creating a new binary column as type logical:
cars <- mtcars
cars$test <- ifelse(cars$mpg >= 25, "Yes", "No")
cars$test2 <- ifelse(cars$mpg >= 25, TRUE, FALSE)
head(cars, 5)
mpg cyl disp hp drat wt qsec vs am gear carb test test2
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 No FALSE
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 No FALSE
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 No FALSE
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 No FALSE
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 No FALSE
You can use the logical comparison operators on Date values.
SteveM
- 2,226
- 3
- 12
- 16