Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Values in DataFrame

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.

like image 268
Austin Avatar asked Jun 01 '26 07:06

Austin


2 Answers

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
like image 76
Mayou Avatar answered Jun 02 '26 21:06

Mayou


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

df[df < 0 & 1:nrow(df) %in% 40:52] <- 0
like image 24
Matthew Plourde Avatar answered Jun 02 '26 19:06

Matthew Plourde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!