[英]R - How to get value from a column based on value from another column of same row
I have a data frame (df) with 8 columns and 1200 rows. 我有一个8列和1200行的数据框(df)。 Among those 8 columns I want to find the minimum value of column 7 and find the corresponding value of column 2 in that particular row where the minimum value of column 7 was found. 在这8列中,我想找到第7列的最小值,并在找到第7列最小值的特定行中找到第2列的相应值。 Also column 2 holds characters so I want a character vector giving me its value. 第2列还包含字符,所以我想要一个字符向量给我它的值。
I found the minimum of column 7 using 我找到了第7列的最小值
min_val <- min(as.numeric(df[, 7]), na.rm = TRUE)
Now how do I get the value from column 2 (variable name of column being 'column.2') corresponding to the row in which column 7 contains value of 'min_val' as calculated above? 现在,如何从第2列(列的变量名为'column.2')获取对应于第7列包含上述计算值'min_val'的行的值?
This might be a trivial question but I am new to R so any help will be much appreciated. 这可能是一个微不足道的问题,但我是R的新手,所以任何帮助将不胜感激。
Use which.min
to get the minimum value index. 使用which.min
获取最小值索引。 Something like : 就像是 :
df[which.min(df[,7]),2]
Note that which.min only returns the first index of the minimum, so if you've got several rows with the same minimal value, you will only get the first one. 请注意,which.min仅返回最小值的第一个索引,因此如果您有多个具有相同最小值的行,则只能获得第一个。
If you want to get all the minimum rows, you can use : 如果要获得所有最小行,可以使用:
df[which(df[,7]==min(df[,7])), 2]
The same answer from juba, but using data.table package (his answer uses just the R base, without the need of loading any libraries). 来自juba的相同答案,但使用data.table包(他的答案仅使用R基,无需加载任何库)。
# Load data.table
library(data.table)
# Get 2nd column's value correspondent to the first minimum value in 7th column
df[which.min(V7), V2]
# Get all respective values in 2nd column correspondent to the minimum value in 7th column
df[V2 == min(V7), V2]
For handling data.frame-like objects, data.table is quite handly and helpful, just like the dplyr package. 对于处理类似数据帧的对象, data.table非常方便有用,就像dplyr包一样。 It's worth to look at them. 值得一看的是它们。
Here I've assumed your colnames were named as V1..V8. 在这里,我假设你的名字命名为V1..V8。 Otherwise, just replace the V7/V2 with the respective column names in 7th and 2nd position of your data, respectively. 否则,只需将V7 / V2分别替换为数据第7位和第2位的相应列名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.