📌  相关文章
📜  返回 R DataFrame 中每一行的最大值的列名

📅  最后修改于: 2022-05-13 01:55:05.262000             🧑  作者: Mango

返回 R DataFrame 中每一行的最大值的列名

在本文中,我们将讨论如何在 R 编程语言中为 DataFrame 中的每一行返回最大值的列名。

例子:

 Column1Column2Column3Max column
Row1200Column1 , Because,  Column2 value and Column 3 value is less than Column1
Row2435Column3 , Because,  Column2 value and Column 1 value is less than Column3
Row31066Column1 , Because,  Column2 value and Column 3 value is less than Column1
Row4954Column1 , Because,  Column2 value and Column 3 value is less than Column1
Row5793Column2 , Because,  Column1 value and Column 3 value is less than Column2

所以对于这个实现,我们将使用 colnames() 和 max.col() 函数

句法:

这里,

  • colnames() 用于获取列名
  • max.col() 用于返回数据框的最大列名

示例: R 程序获取所有行中最大的列名

R
# create  a dataframe with 3 columns and 3 rows
data = data.frame(subject1=c(91, 62, 93),
                  subject2=c(98, 79, 70),
                  subject3=c(100, 78, 98))
  
  
# get the largest column name in each row
print(colnames(data)[max.col(data)])


R
# create  a dataframe with 4 columns and 3 rows
data = data.frame(subject1=c(91, 62, 93, 56, 78),
                  subject2=c(98, 79, 70, 56, 78),
                  subject3=c(100, 78, 98, 56, 71))
  
# get the largest column name in each row
print(colnames(data)[max.col(data)])


输出:

[1] "subject3" "subject2" "subject3"

示例: R 程序获取所有行中最大的列名

电阻

# create  a dataframe with 4 columns and 3 rows
data = data.frame(subject1=c(91, 62, 93, 56, 78),
                  subject2=c(98, 79, 70, 56, 78),
                  subject3=c(100, 78, 98, 56, 71))
  
# get the largest column name in each row
print(colnames(data)[max.col(data)])

输出:

[1] "subject3" "subject1" "subject3" "subject1" "subject2"