Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update column rows based on rows in another column

Tags:

r

I have a dataset as given below in R. I am trying to update the empty cell in the Description column for '0' values in column Value.

 Criteria     Value   Description 
 Success       0                                      
 Success      21      look up
 Success      20      repeat
 Success      19      What is this
 Success      18      Transition
 Success      17      Program
 Success       0              

I would appreciate any help to solve this. The output that I am trying to get is given below:

 Criteria     Value   Description 
 Success       0      TEST                             
 Success      21      look up
 Success      20      repeat
 Success      19      What is this
 Success      18      Transition
 Success      17      Program
 Success       0      TEST 
like image 557
Sree Avatar asked Feb 06 '26 17:02

Sree


2 Answers

There are several options:

Base R - Option 1

mydf$Description[mydf$Value == 0] <- "TEST"

Base R - Option 2

mydf$Description <- ifelse(mydf$Value == 0, "TEST", mydf$Description)

dplyr - if_else()

library("dplyr")
mydf <- mydf %>% mutate(Description = if_else(Value == 0, "TEST", Description))

dplyr - case_when()

Useful when a number of if statement need to be evaluated.

library("dplyr")
mydf <- mydf %>% mutate(
  Description = case_when(
    Value == 0 ~ "TEST",
    TRUE ~ Description
    )
  )
like image 111
Josh Gilfillan Avatar answered Feb 09 '26 08:02

Josh Gilfillan


Could use an ifelse() statement.

Assuming your dataframe is called "dataset", you can use an ifelse() statement to check the Value column for 0. If it is a 0, it will input the value "TEST" in the Description column. If it is not a 0 (else), then it will just input what value is already there in the column.

 dataset$Description <- ifelse(dataset$Value == 0, 
                               "TEST" , 
                               dataset$Description)
like image 29
Pete Avatar answered Feb 09 '26 09:02

Pete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!