Try to search your question here, if you can't find : Ask Any Question Now ?

Conditional replacement of a string in data frame

HomeCategory: stackoverflowConditional replacement of a string in data frame
Avatargaurav asked 1 month ago
DF <- data.frame("ID" = c(901, 902, 903, 904, 909), "INT" = c(0, 1, 0, 1, 1))

> DF
   ID INT
1 901   0
2 902   1
3 903   0
4 904   1
5 909   1

I want to replace “9” in the ID column when INT = 1, so, it should look like following:

 New_DF
   ID INT
1 901   0
2 802   1
3 903   0
4 804   1
5 809   1

I have tried this

if(DF$INT == "1") {
  gsub("^9", "8", DF$ID) 
}

It gives me the following error:

Warning message:
In if (DF$INT == “1”) { :
the condition has length > 1 and only the first element will be used

1 Answers
Best Answer
AvatarMikhail answered 1 month ago
Your Answer

4 + 8 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com