根据R中另一列中的条件从一列中获取值



我有一个这样的数据表:

DT <- data.table(score=c(78, 93, 88, 50), IQ=c(101, 95, 89, 90))
# DT output
score, IQ
78, 101
93, 95
88, 89
50, 90

我想得到IQ最高的score,例如这里的max(IQ)=101,所以我们得到78。

有没有一种方法可以通过创建一个新表并使用:来做到这一点

new_DT <- DT[, list(scoreMaxIQ = ...)]

即在list(...)内,我们为IQ最高的分数创建新的变量scoreMaxIQ

你可以做:

DT[,.(IQ, score,maxIQ = IQ[which.max(IQ)],scoreMaxIQ =score[which.max(IQ)] )]
IQ score maxIQ scoreMaxIQ
1: 101    78   101         78
2:  95    93   101         78
3:  89    88   101         78
4:  90    50   101         78

注意必须转换为数字,因为"101"<"95"处于字符模式。

最新更新