[英]Obtain value from a column based off condition in another column in R?
I have a data table like this:我有一个这样的数据表:
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
I want to obtain the score
at which IQ
is the highest, eg here max(IQ)=101
so we would get 78.我想获得IQ
最高的score
,例如这里max(IQ)=101
所以我们会得到 78。
Is there a way to do this by creating a new table and using:有没有办法通过创建一个新表并使用:
new_DT <- DT[, list(scoreMaxIQ = ...)]
ie inside list(...)
we create a new variable scoreMaxIQ
for the score at which IQ is the highest?即在list(...)
我们为 IQ 最高的分数创建了一个新变量scoreMaxIQ
?
You could do:你可以这样做:
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
Note the necessary conversion to numeric because "101"<"95"
in character mode.请注意必要的数字转换,因为字符模式下的"101"<"95"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.