![](/img/trans.png)
[英]is there a way in R such that the value of a column should be the one above if it meets a certain criteria in another column
[英]Is there a better way to find the percent of one column that meets a criteria for each value in another column for a data frame in R?
我有一个数据帧,其grade.equivalent
和scaled.score
,均为数值。 我想为每个年级或以上的所有学生找到等于或高于给定scaled.score
的学生grade.equivalent
。
例如,给定以下数据框:
df.ex <- data.frame(grade.equivalent=c(2.4,2.7,3.1,2.5,1.4,2.2,2.3,1.7,1.3,2.2),
scaled.score=c(187,277,308,268,236,305,298,246,241,138)
)
我想知道每个grade.equivalent
等于或高于该grade.equivalent
的学生中,得分高于301的学生中有grade.equivalent
。
为此,我执行了以下操作:
find.percent.basic <- function(cut.ge, data, cut.scaled.score){
df.sub <- subset(data, grade.equivalent >= cut.ge & !is.na(scaled.score))
denom <- nrow(df.sub)
df.sub <- subset(df.sub, scaled.score >= cut.scaled.score)
numer <- nrow(df.sub)
return(numer/denom)
}
grade.equivs <- unique(df.ex$grade.equivalent)
grade.equivs <- grade.equivs[order(grade.equivs)]
just.percs <- sapply(grade.equivs, find.percent.basic, data=df.ex, cut.scaled.score=301)
new.df <- data.frame(grade.equivalent=grade.equivs, perc=just.percs)
我计划将其包装在一个函数中,并与plyr一起使用。
我的问题是,有更好的方法吗? 似乎这可能是r的基函数或我不知道的通用包。
感谢您的任何想法。
编辑以澄清问题上面的代码产生以下结果,这是我想要的结果:
grade.equivalent perc
1 1.3 0.2000000
2 1.4 0.2222222
3 1.7 0.2500000
4 2.2 0.2857143
5 2.3 0.2000000
6 2.4 0.2500000
7 2.5 0.3333333
8 2.7 0.5000000
9 3.1 1.0000000
根据@DWin的观察结果,第二次编辑以进行澄清
布尔值的平均值是正确的百分比,因此应执行以下操作:
mean(data$scaled.score >= cut.ss, na.rm=TRUE)
如您的评论所述,是的,这正是您需要做的。 我选择对scaled.score
访问稍有不同,但没有实际区别。
gs <- sort(unique(df.ex$grade.equivalent))
ps <- sapply(gs, function(cut.ge) {
mean(df.ex$scaled.score[df.ex$grade.equivalent>=cut.ge] >= 301, na.rm=TRUE)
})
data.frame(gs, ps)
# gs ps
# 1.3 0.2000000
# 1.4 0.2222222
# 1.7 0.2500000
# 2.2 0.2857143
# 2.3 0.2000000
# 2.4 0.2500000
# 2.5 0.3333333
# 2.7 0.5000000
# 3.1 1.0000000
我认为这不适用于plyr
的split-apply-combine方法,因为您不能将每个等值的数据拆分为离散的子集,相反,某些行会出现在多个子集。
另一种选择是将分数(或整个数据框,如果需要)自己分割为所需的部分,然后应用所需的任何功能; 这将是与plyr
相同的方法,尽管更多是手工操作。
scores <- lapply(gs, function(x) df.ex$scaled.score[df.ex$grade.equivalent>=x])
sapply(scores, function(x) mean(x>301, na.rm=TRUE))
最后的选择是将它们放到开始,然后计算一个累积平均值,并删除重复的grade.equivalent
值,像这样。
df2 <- df.ex[rev(order(df.ex$grade.equivalent)),]
df2$perc <- cumsum(df2$scaled.score>301)/1:nrow(df2)
df2 <- df2[nrow(df2):1,c("grade.equivalent", "perc")]
df2[!duplicated(df2$grade.equivalent),]
with(df.ex, tapply(scaled.score, INDEX=grade.equivalent,
FUN=function(s) 100*sum(s>301)/length(s) ) )
#1.3 1.4 1.7 2.2 2.3 2.4 2.5 2.7 3.1
# 0 0 0 50 0 0 0 0 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.