0

我有一个 18528 行和 3 列的数据框,如下所示:

Sample  Target  Value
100      A       21.5
100      A       20.5
100      B       19.5
100      B       19.75
100      B       18.15
100      B       21.95
200      A       21.1
200      A       21.6
200      B       23.5
200      B       20.75
100      C       21.25
100      C       22.0
100      C       18.33
100      C       21.84

我需要计算每组中值之间的差异:

Sample  Target  Value   dif
100      A       21.5   1
100      A       20.5   1
100      B       19.5   0.25
100      B       19.75  1.6
100      B       18.15  3.8
100      B       21.95  2.45
200      A       21.1   0.5
200      A       21.6   0.5
200      B       23.5   2.75
200      B       20.75  2.75
100      C       21.25  0.75
100      C       22.0   3.67
100      C       18.33  3.51
100      C       21.84  0.59

然后,如果差异大于 2,则将该值设为“NA”,如:

Sample  Target  Value   dif
100      A       21.5   1
100      A       20.5   1
100      B       19.5   0.25
100      B       19.75  1.6
100      B       18.15  3.8
100      B       NA     2.45
200      A       21.1   0.5
200      A       21.6   0.5
200      B       NA     2.75
200      B       NA     2.75
100      C       21.25  0.75
100      C       22.0   3.67
100      C       NA     3.51
100      C       21.84  0.59

我用combn来计算差异,但我得到了错误,我认为原因可能是组(2和4)中的长度不同。提前致谢

4

1 回答 1

0

You can get desired output using dplyr package. If you don't have it installed first run command install.packages("dplyr") or install it manually.

Then what we have:

require("dplyr")

mydf <- read.table(text = "
Sample  Target  Value
100      A       21.5
100      A       20.5
100      B       19.5
100      B       19.75
100      B       18.15
100      B       21.95
200      A       21.1
200      A       21.6
200      B       23.5
200      B       20.75
100      C       21.25
100      C       22.0
100      C       18.33
100      C       21.84", header = T)

mydf1 <- mydf %>% group_by(Sample, Target) %>% 
  mutate(ValueShifted = c(Value[-1], Value[1]) ) %>%
  mutate(dif = abs(Value - ValueShifted) ) %>%
  mutate(NewValue = c(1, NA)[(as.numeric(dif > 2)+1)] * Value )

> mydf1
Source: local data frame [14 x 6]
Groups: Sample, Target

   Sample Target Value ValueShifted  dif NewValue
1     100      A 21.50        20.50 1.00    21.50
2     100      A 20.50        21.50 1.00    20.50
3     100      B 19.50        19.75 0.25    19.50
4     100      B 19.75        18.15 1.60    19.75
5     100      B 18.15        21.95 3.80       NA
6     100      B 21.95        19.50 2.45       NA
7     200      A 21.10        21.60 0.50    21.10
8     200      A 21.60        21.10 0.50    21.60
9     200      B 23.50        20.75 2.75       NA
10    200      B 20.75        23.50 2.75       NA
11    100      C 21.25        22.00 0.75    21.25
12    100      C 22.00        18.33 3.67       NA
13    100      C 18.33        21.84 3.51       NA
14    100      C 21.84        21.25 0.59    21.84
于 2015-04-09T13:02:21.993 回答