blueblood blueblood - 4 months ago 16
R Question

Looping a column in a dataframe while changing its value

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


So myDataFrame is at th moment is

column1---------column 2





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


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

myDataFrame$column2 <- with(myDataFrame, ifelse(column1 >= x, "b", "a"))