根据 R 中另一列的条件从一列获取值?
Obtain value from a column based off condition in another column in R?
我有这样的数据table:
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
我想获得 score
的 IQ
是最高的,例如这里 max(IQ)=101
所以我们会得到 78.
有没有办法通过创建一个新的 table 并使用:
new_DT <- DT[, list(scoreMaxIQ = ...)]
即在 list(...)
中,我们为智商最高的分数创建了一个新变量 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"
在字符模式下。
我有这样的数据table:
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
我想获得 score
的 IQ
是最高的,例如这里 max(IQ)=101
所以我们会得到 78.
有没有办法通过创建一个新的 table 并使用:
new_DT <- DT[, list(scoreMaxIQ = ...)]
即在 list(...)
中,我们为智商最高的分数创建了一个新变量 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"
在字符模式下。