3

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 
zx8754
  • 52,746
  • 12
  • 114
  • 209
Sree
  • 65
  • 2
  • 7
  • 1
    You want to fill the column with what? Also provide the output of `dput(yourdataframe)`. Please read [How to make a great reproducible example in R?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) to improve quality of your question. – M-- Aug 15 '17 at 21:35
  • 3
    mydf$Description[mydf$Value == 0] <- "TEST" – Josh Gilfillan Aug 15 '17 at 21:43
  • @Masoud: Thanks for sharing the link. This is a good article; will take input and reframe my question to be reproducible. – Sree Aug 15 '17 at 21:52

2 Answers2

3

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
    )
  )
zx8754
  • 52,746
  • 12
  • 114
  • 209
Josh Gilfillan
  • 4,348
  • 2
  • 24
  • 26
  • Thank you very much. I had some issue with the Description since they were "factors" in my case. Had to convert them to characters before using this. Appreciate your multiple solutions. – Sree Aug 16 '17 at 07:41
1

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)
Pete
  • 168
  • 1
  • 9
  • `ifelse` is quiet inefficiency, maybe try `dataset$Description[dataset$Value==0]='Test'` or `dataset$Description[dataset$Value%in%0]='Test'` – BENY Aug 15 '17 at 21:59