R:通过对ID进行分组来计算列中值

时间:2015-05-08 21:33:38

标签: r dplyr na median

继续我之前的post,现在我想按ID分组(仅适用于第3列)并计算列的中位数(Point_B),然后使用列中的每个值减去中值(Point_B) )到其各自的小组。 NA仍应归还。

注意:我希望ID分组仅应用于Point_B列而不应用于Point_A,因为我想计算整个Point_A列的中值并用Point_A中的值减去它。

例如

ID <- c("A","A","A","B","B","B","C","C","C") 
Point_A <- c(1,2,NA,1,2,3,1,2,NA) 
Point_B <- c(1,2,3,NA,NA,1,1,1,3)

df <- data.frame(ID,Point_A ,Point_B)


+----+---------+---------+
| ID | Point_A | Point_B |
+----+---------+---------+
| A  | 1       | 1       |
| A  | 2       | 2       |
| A  | NA      | 3       |
| B  | 1       | NA      |
| B  | 2       | NA      |
| B  | 3       | 1       |
| C  | 1       | 1       |
| C  | 2       | 1       |
| C  | NA      | 3       |
+----+---------+---------+

我之前发布的解决方案计算了中位数而没有按ID分组。这是

library(dplyr)
 df %>%
     mutate_each(funs(median=.-median(., na.rm=TRUE)), -ID)

期望输出

+----+---------+---------+
| ID | Point_A | Point_B |
+----+---------+---------+
| A  | -1      | -1      |
| A  | 0       | 0       |
| A  | NA      | 1       |
| B  | -1      | NA      |
| B  | 0       | NA      |
| B  | 1       | 0       |
| C  | -1      | 0       |
| C  | 0       | 0       |
| C  | NA      | 2       |
+----+---------+---------+

我们如何通过ID分组获取Column3中的值?

1 个答案:

答案 0 :(得分:2)

我想要group_by,我想(关注@ docendodiscimus&#39;建议):

demed <- function(x) x-median(x,na.rm=TRUE)

df %>% 
  mutate_each(funs(demed),Point_A) %>%
  group_by(ID) %>%  
  mutate_each(funs(demed),Point_B)

  ID Point_A Point_B
1  A      -1      -1
2  A       0       0
3  A      NA       1
4  B      -1      NA
5  B       0      NA
6  B       1       0
7  C      -1       0
8  C       0       0
9  C      NA       2

我更喜欢类似的data.table代码。它的语法需要多次写入变量名,但括号少得多:

require(data.table)
DT <- data.table(df)

DT[,Point_A:=demed(Point_A)
][,Point_B:=demed(Point_B)
,by=ID]