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.

4

2 回答 2

4

或者简单地说:

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

这是一个测试:

 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

要仅将第 2 行和第 3 行的负值替换为 0,您可以执行以下操作:

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

你得到

 #> test
 #  A B C D
 #1 1 4 1 7
 #2 2 0 2 8
 #3 0 5 3 0
于 2013-10-29T17:19:41.267 回答
2

这是另一种方式,利用 R 的回收行为。

df[df < 0 & 1:nrow(df) %in% 40:52] <- 0
于 2013-10-29T17:40:54.907 回答