3

So a quick question jumping off of this one....

Fast replacing values in dataframe in R

If I want to do this replace but only for certain rows of my data frame, is there a way to add a row specification to:

df [df<0] =0

Something like applying this to rows 40-52 (Doesn't work):

 df[df[40:52,] < 0] = 0

Any suggestions? Much appreciated.

0

2 Answers 2

4

Or simply:

 df[40:52,][df[40:52,] < 0] <- 0

Here is a test:

 test = data.frame(A = c(1,2,-1), B = c(4,-8,5), C = c(1,2,3), D = c(7,8,-9))

 #> test
 #   A  B C  D
 #1  1  4 1  7
 #2  2 -8 2  8
 #3 -1  5 3 -9

To replace the negative values with 0 for only rows 2 and 3, you can do:

 test[2:3,][test[2:3,] < 0] <- 0

and you get

 #> test
 #  A B C D
 #1 1 4 1 7
 #2 2 0 2 8
 #3 0 5 3 0
Sign up to request clarification or add additional context in comments.

Comments

2

This is another way, utilizing R's recycling behavior.

df[df < 0 & 1:nrow(df) %in% 40:52] <- 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.