Sree Sree -3 years ago 96
R Question

Update column rows based on rows in another column in 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


thanks,

Answer Source

There are several options:

Base R - Option 1

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

Base R - Option 2

mydf$Description <- if.else(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
    )
  )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download