简体   繁体   English

根据 R 中的单元格值和列名查找行名

[英]Find row name based on cell value & column name in R

Say I have this data frame df :假设我有这个数据框df

   |c1 |c2 |c3 |c4 |
r1 | 2 | 3 | 3 | 5 |
r2 | 5 | 8 | 6 | 1 |

Note that all the column values are unique, but some cell values repeat ( 3 and 5 ).请注意,所有列值都是唯一的,但某些单元格值重复( 35 )。 I'd like to find out the name of the row containing 5 in column c4 (in this case, it would return "r1" ).我想找出c4列中包含5的行的名称(在这种情况下,它将返回"r1" )。

I've found SO questions about finding the row name based on just cell value, which doesn't work when different cells can have the same values.我发现了关于仅根据单元格值查找行名的问题,当不同的单元格可以具有相同的值时,这不起作用。 I've also found questions about finding the row index based on the cell value and column index , but I need to be able to do this in a scenario where I might know the indices that correspond to the column/row names.我还发现了有关根据单元格值和列索引查找行索引的问题,但我需要能够在我可能知道与列/行名称对应的索引的情况下执行此操作。 But based on the answers I found for those questions, I've tried the following 4 methods, and none have worked:但是根据我为这些问题找到的答案,我尝试了以下 4 种方法,但都没有奏效:

# 1
df[max(df$c4), "c4"]

# 2
which(df == max(df$c4), arr.ind=TRUE)

# 3
rownames(df)[max(df$c4), "c4"]

# 4
row(df$c4, max(df$c4))

Thanks in advance!提前致谢!

If you want row name based on max value in c4 use:如果您想要基于c4中的最大值的行名,请使用:

rownames(df)[which.max(df$c4)]
#[1] "r1"

Or if there could be multiple max value use:或者如果可能有多个最大值使用:

rownames(df)[df$c4 == max(df$c4)]

data数据

df <- structure(list(c1 = c(2L, 5L), c2 = c(3L, 8L), c3 = c(3L, 6L), 
c4 = c(5L, 1L)), class = "data.frame", row.names = c("r1", "r2"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM