Q:

Is the syntax of my for-loop in R correct?

My data is as follows (I call it data1):
X_4_2_1_a  X_4_2_2_a
5          7
999        999
998        998
2          998
1          NA
NA         999

I want to apply the following function to the data:
na.zero <- function (x) {
  x[is.na(x)] <- 0
  return(x)
}

And I want to use the following loop:
for (i in seq(1, 2, 1)) {
  data1$X_4_2_i_a <- na.zero(data1$X_4_2_i_a)
}

But it is not working. Could someone please assist?

A:

the problem is with the variable you are trying to access in the data frame, you trying to access X_4_2_i_a which is not increment i in each iteration because its a string; Which is not the way to iterate on increasing labels in data frame.
You can consider creating a variable in each iteration using paste and then access it

paste("X_4_2_", i, "_a", sep = "")

na.zero <- function (x) {
  x[is.na(x)] <- 0
  return(x)
}

df = data.frame("X_4_2_1_a"=c(5,999,998,2,1,NA), "X_4_2_2_a"=c(5,999,998,NA,1,NA))

for (i in seq(1, 2, 1)) {
    nn = paste("X_4_2_", i, "_a", sep = "")
    df[nn] <- na.zero(df[nn])
}

print(df)

will produce:
  X_4_2_1_a X_4_2_2_a
1         5         5
2       999       999
3       998       998
4         2         0
5         1         1
6         0         0

A solution that doesnt invovle loop is:
df = sapply(df, na.zero)
print(df)

which will produce the same output

