Your code uses print
which immediately prints the values – that’s not what you want. You want to separately (a) calculate the result and (b) write the result table into a file.
First, here’s a function which transforms a single row:
get_dist = function (row) {
index = which(row > 0)[1]
if (is.na(index)) NA else switch(index, 0, 2000, 5000)
}
It works by looking which is the first index that is >0, if any. switch
translates that index into the distance.
Now we apply (literally) the function to the input matrix:
result = apply(input, 1, get_dist)
But this result is actually a vector:
result
# 001 002 003 004
# NA 5000 2000 0
– we want a matrix or data frame:
result = data.frame(distance = result)
result
# distance
# 001 NA
# 002 5000
# 003 2000
# 004 0
And now we can write it to a file:
write.csv(result, csv_file, append = TRUE)