I have a dataframe called 'df' with two columns: 'week' and 'stock'
When column "Week" is 0, I want to change all values on colum "stock" to 0.
I can do it with base R with:
df[df$week == 0, "stock"] = 0
Use the ifelse()
df$stock<- ifelse(df$week == 0, 0, df$stock)
or in dplyr()
df %>%
mutate(stock=replace(stock, week==0, 0)) %>%
as.data.frame()
Sample data:
df<-data.frame("stock"=c(12334, 3456, 5678, 223232, 456, 678, 567, 1),
"week"=c(0, 1,2,0,4,5,0,7))
We can use replace
to change the values to 0 that corresponds to week==0.
df %>% mutate(stock=replace(stock, week==0, 0))