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.

Community
  • 1
  • 1
Austin
  • 73
  • 1
  • 7

2 Answers2

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
Mayou
  • 8,498
  • 16
  • 59
  • 98
2

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

df[df < 0 & 1:nrow(df) %in% 40:52] <- 0
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113