-4

I am trying to loop through all the rows of a column in a DataFrame. I read in the csv using data.table. I am new to R and was wondering what way I would go about doing something like this:

for i in row_2_of_dataframe: 
 if i == 0: 
  #Do something to that value
 else: 
  #Leave it the way it is 

Any help would be great.

Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36
n_lyons10
  • 73
  • 1
  • 11
  • Please give a [mcve] – jogo Jul 10 '17 at 14:31
  • When using R, we rarely explicitly loop through data.frames. It would be better if you provided some sort of [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample data input and the desired output for that input. – MrFlick Jul 10 '17 at 14:31

2 Answers2

0

I would recommend using the ifelse() function. For example;

mydf$column_name <- ifelse(mydf$column_name == 0, "do something",mydf$column_name)
Josh
  • 1,800
  • 3
  • 15
  • 21
-1
frame <- data.frame(x = as.character(rep("bye", 11)), 
                    y = as.character(0:10),
                    stringsAsFactors = FALSE)

for (i in 1:length(frame[, 2])) {
  if (frame[, 2][i] == 0) {
    frame[, 2][i] <- "hi"
  }
}

You don't even really need an else statement.

Furthermore,

frame[, 2] 

selects the second column and turns it into a vector.

frame[, 1] 

would select the first column.

frame[1, ] 

would select the first row.

And so on.

Cheers.

Odysseus210
  • 468
  • 3
  • 9