1

The question is:

1) If there is a data frame with 5 rows as follow:

x = c(0,1,3,4,8)
y = c(3,4,6,8,9)
z = c(5,7,3,6,10)
xyz = data.frame(rbind(x,y,z))

x  0  1  3  4  8
y  3  4  6  8  9
z  5  7  3  6 10

I want to replace the numbers with 0 if they are smaller than the mean of every row using for loop in R. For example, if (xyz[i,] < mean(xyz[i,] ) then:

x  0  0  0  4  8
y  0  0  6  8  9
z  0  7  0  0 10

I use the for loop of R as follow:

for(i in 1:3)
{
  j = c(1:5)
  if(xyz[i,j] < rowMeans(xyz[i,]))
     xyz[i,j] = 0
}

Warning messages: 1: In if (xyz[i, j] < rowMeans(xyz[i, ])) xyz[i, j] = 0 : the condition has length > 1 and only the first element will be used…… Any help is appreciated!

0

2 Answers 2

4

You don't need a for loop. You can simply do,

xyz[xyz < rowMeans(xyz)] <- 0
Sign up to request clarification or add additional context in comments.

Comments

1

Your error is that you need to loop over j as well as i:

for(i in 1:3){
  for (j in 1:5) {
    if(xyz[i,j] < rowMeans(xyz[i,]))
    xyz[i,j] = 0
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.