0

I have created a for loop that goes through each row of a certain column. I want to change the information written in that cell depending on certain conditions, so I implemented an if/else statement.

However, the current problem is that the data is printing out one specific outcome: B.

I tried to combat this problem by exporting using write.csv and importing using read.csv. When I applied the head() function though, I still got Medium for all rows.

Would anyone be able to help with this please?

Kaia Zhai
  • 1
  • 2
  • You aren't assigning values by row. `cool$b <- "Medium"` will assign Medium to the entire column b. Use `cool[i, "b"]` to assign. – at80 Nov 17 '20 at 03:55
  • Hmm, thanks for helping. I tried to do this, but then I got an error in "if (...) ", where it mentions that the argument is of length zero. – Kaia Zhai Nov 17 '20 at 04:24
  • Check `?cut` or `?findInterval`. See this example - https://stackoverflow.com/questions/12979456/r-code-to-categorize-age-into-group-bins-breaks – Ronak Shah Nov 17 '20 at 04:39

2 Answers2

0

you do not need to use a for loop for creating a new column based upon conditions. You could simply use this:

cool$b<-cool$a

cool$b[cool$a <3]<-"low"

cool$b[cool$a >= 3 & school_data2019$Taxable.Income< 4]<-"Medium"

cool$b[cool$a >= 4 & school_data2019$Taxable.Income < 5]<-"Rich"

cool$b[cool$a >5]<-"Very Rich" 
0

Walkthrough the following example step by step. You need to assign for loop variable correctly. Could you show us the data frame where you are changing values? That would be helpful.

#creating new data frame
Df <- data.frame(a=c(1,2,3,4,5),b=c(2,3,5,6,8),c=c(10,4,2,3,7))   


for (k in 1:dim(Df)[1]) {
#see how k is utilised and Df$Newcolumn creates new column in existing dataframe
  if (Df$a[k]<=3) {
    Df$Newcolumn[k] <- "low"
  }else if (Df$a[k]>3 && Df$a[k]<=6) {
    Df$Newcolumn[k] <- "medium"
  }
    
}
DD11
  • 75
  • 8