'Change negative values to zero using for loop

I should solve this problem with R, but I'm not really familiar with it so how to solve it?

A vector of length 10 called " vec " has been defined. Write a for loop that changes every negative element of vec to a zero.

How do I do this? I've tried this sort of things but it doesn't work.

x <- 0
 for(var in 1:10){
  if  (vec x < 0) <- 0
}
r


Solution 1:[1]

Try this:

for (i in 1:length(vec)){
  vec[i] = replace(vec[i], vec[i]<0, 0)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deepansh Arora