0

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
RoyBatty
  • 306
  • 1
  • 7

2 Answers2

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))
Rfanatic
  • 2,224
  • 1
  • 5
  • 21
0

We can use replace to change the values to 0 that corresponds to week==0.

df %>% mutate(stock=replace(stock, week==0, 0))
Levon Ipdjian
  • 786
  • 7
  • 14