简体   繁体   English

从基于 R 中另一列中的条件的列中获取值?

[英]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.

相关问题 "根据 R 中另一列的条件求和(或不求和)一个值" - Sum (or not) a value based on condition of another column in R 根据 R 中另一列的最小值获取一列的对应值 - obtain corresponding value of one column based on minimum value of another in R R data.table如何基于另一列的值从多个列之一(按列NAME)获取VALUE - R data.table How to obtain the VALUE from one of many columns (by column NAME), based on the value of another column R:根据另一列的文本条件更新列 - R: Update Column Based on Text Condition from Another Column 如何根据R中另一列的条件过滤列 - How to filter a column based on a condition from another column in R 根据另一列的条件在 R 中添加新列 - add new column in R based on condition from another column 如何在R中第一次出现另一个条件后根据条件的第二次出现从列中获取值? - How to get a value from a column based on second occurrence of a condition after first occurrence of another condition in R? R,从另一个表中获取指向列的值(更快) - R, obtain pointed column value from another table (faster) 根据R中另一列的条件求和 - Sum a column based on condition in another column in R 使用基数 R 根据另一个条件中的值从表中删除行 - Removing rows from a table based off values in another conditional on a value in a separate column using base R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM