How to change values to N/A in R?

Part of my dataset looks something like below:
enter image description here

How do I filter this to replace values under the heading “positive” to N/A from week ending the 19-10-20?

Thanks!


Assuming that your date is in format day-month-year (dmy), and that the column Week Ending of your dataset is not of Date class, you can run the code below to change all dates after 19-10-20, including it, to NA.

library(lubridate)
library(tidyverse)
library(magrittr)

data %<>% mutate(`Week Ending` = dmy(`Week Ending`)) %>%
     mutate(Positive = if_else(`Week Ending` >= dmy("19-10-20"), NA, `Week Ending`)

Welcome to Stack Overflow! In the future, please try to post a reproducible example, which can help respondents better understand and diagnose your issues.

To answer your question, you can accomplish this using selection syntax in R. Below is a reproducible example for your desired outcome.

Week_ending<-c("12-10-20","19-10-20", "26-10-20")
Positive<-c(5.6,7.9,2.4)
Negative<-c(3.5,4.9,1.7)

df<-data.frame(Week_ending=format(as.Date(Week_ending, format="%d-%m-%y"),"%d-%m-%y"), Positive=Positive, Negative=Negative)
df$Positive[df$Week_ending=="19-10-20"]<-NA # This is the line that accomplishes what you are after
df

In the line that I have flagged in the code block above, I use the dollar sign $ and square brace [] operators.

The dollar sign means select a column, and the square braces can be interpreted as a more generic approach to selection. Breaking down the syntax

df$Positive means "select the Positive column from the df dataframe"

[df$Week_ending=="19-10-20"]means "where the value of the Week_ending column in the df dataframe is equal to 19-10-20

<-NA simply means assign these values NA

In plain English the whole line means "Make the value of Positive NA for any rows corresponding to the Week_ending 19-10-20 "