Austin
Austin

Reputation: 73

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.

Upvotes: 3

Views: 844

Answers (2)

Matthew Plourde
Matthew Plourde

Reputation: 44614

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

df[df < 0 & 1:nrow(df) %in% 40:52] <- 0

Upvotes: 2

Mayou
Mayou

Reputation: 8848

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

Upvotes: 4

Related Questions