1

I'm quite new to R, picked it up less than two weeks ago and was wondering why this didn't work. Basically what I'm trying to do is to loop through the new added column, compare a value of another column in the same row, and based on a condition, change the value in the column I'm looping.

myDataFrame["column2"] <- "a"
refValue = x
for(i in nrow(myDataFrame){
  if(column1[i] >= refValue){
    column2[i] <- "b"
}}

Tried to run it but the value doesn't change

View(MyDataFrame)

So myDataFrame is at th moment is
column1---------column 2
someValue------a
someValue------a
someValue------a
someValue------a

after it finished looping based on a condition which is the value of the corresponding row in column1, I want to change some of the 'a's to 'b's

blueblood
  • 143
  • 8
  • 1
    You don't need a loop to do this. Please provide a reproducible example with expected output. what is `x` in `refValue = x` ? Are you comparing character elements. – akrun Aug 29 '16 at 08:51
  • Thank you for helping but the solution @Ronak Shah provide works. – blueblood Aug 29 '16 at 08:59
  • Other possible duplicate is [this](http://stackoverflow.com/questions/5824173/replace-a-value-in-a-data-frame-based-on-a-conditional-if-statement-in-r) – akrun Aug 29 '16 at 09:07

1 Answers1

1

No need to use loop for this. You can replace your code with

myDataFrame$column2 <- with(myDataFrame, ifelse(column1 >= x, "b", "a"))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213