Looping through a column and returning value

Viewed 243

I want to loop through one of the columns in my data frame and check a condition, then replace 0 or 1. The code is :

for (i in v$R){
     if( is.na(v$R) ==TRUE ){v$V5 = 0}else{v$V5=1}
}

But I get an error. The data frame named 'v' is as follow. The V5 has NA values and I want to replace with 0 if values in R columns are NA, and else replace with 1. How can I do that?

A B R V5
1 2 3 NA
4 5 NA NA
2 Answers
  • You can try ifelse like below
df <- within(df,V5 <- ifelse(is.na(R),0,1))

or + (which converts logical value to numerical ones)

df <- within(df,V5 <- +!is.na(R))

such that

> df
  A B  R V5
1 1 2  3  1
2 4 5 NA  0
  • If you would like to use loops, you can try
for (i in seq_along(df$R)){
  if( is.na(df$R[i]) ==TRUE ){df$V5[i] = 0}else{df$V5[i]=1}
}

DATA

df <- structure(list(A = c(1L, 4L), B = c(2L, 5L), R = c(3L, NA), V5 = c(NA, 
NA)), class = "data.frame", row.names = c(NA, -2L))

Try this:

v$V5 <- ifelse(is.na(v$R), 0, 1)
Related