开发者

Assign pass/fail value based on mean in large dataset

this might be a simple question but I was hoping someone could point me in the right direction. I have a sample dataset of:

dfrm <- list(L = c("A","B","P","C","D","E","P","F"), J=c(2,2,1,2,2,2,1,2), K=c(4,3,10,16,21,3,17,2))
 dfrm <-as.data.frame(dfrm)
 dfrm
  L J  K
1 A 2  4
2 B 2  3
3 P 1 10
4 C 2 1开发者_C百科6
5 D 2 21
6 E 2  3
7 P 1 17
8 F 2  2

Column J specifies the type of variable that is defined in K. I want to be able to take the mean of the K values that have a 1 assigned next to them. In this example it would be 10 and 17

T = c(10,17)
mean(T)
13.5

Next I want to be able to assign a pass/fail rank, where pass = 1, fail = 0 to identify whether the number in column K is larger than the mean.

The final data set should look like:

cdfrm <- list(L = c("A","B","P","C","D","E","P","F"), J=c(2,2,1,2,2,2,1,2), K=c(4,3,10,16,21,3,17,2),C = c(0,0,0,1,1,0,1,0))
cdfrm <-as.data.frame(cdfrm)
 cdfrm
  L J  K C
1 A 2  4 0
2 B 2  3 0
3 P 1 10 0
4 C 2 16 1
5 D 2 21 1
6 E 2  3 0
7 P 1 17 1
8 F 2  2 0

this seems so basic, i am sorry guys, I just don't know what I am overthinking.


There are two steps in the solution. The first is to calculate the mean for the value you are interested in. In other words, take the mean of a subset of values in your data.frame. R has a handy function to calculate subsets, called subset. Here it is in action:

meanK <- mean(subset(dfrm, subset=J==1, select=K))
meanK
K 
13.5 

Next, you want to compare column K in your data frame with the mean value we have just calculated. This is a straightforward vector comparison:

dfrm$Pass <- dfrm$K>meanK
dfrm
L J  K  Pass
1 A 2  4 FALSE
2 B 2  3 FALSE
3 P 1 10 FALSE
4 C 2 16  TRUE
5 D 2 21  TRUE
6 E 2  3 FALSE
7 P 1 17  TRUE
8 F 2  2 FALSE


Here's how to do it in one line

transform(dfrm, C = K > sapply(split(dfrm$K, dfrm$J), mean)[J])

split groups the values of K according to the values of J and sapply(..., mean) calculates group wise means.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜