返回 R DataFrame 中每一行的最大值的列名
在本文中,我们将讨论如何在 R 编程语言中为 DataFrame 中的每一行返回最大值的列名。
例子: Column1 Column2 Column3 Max column Row1 2 0 0 Column1 , Because, Column2 value and Column 3 value is less than Column1 Row2 4 3 5 Column3 , Because, Column2 value and Column 1 value is less than Column3 Row3 10 6 6 Column1 , Because, Column2 value and Column 3 value is less than Column1 Row4 9 5 4 Column1 , Because, Column2 value and Column 3 value is less than Column1 Row5 7 9 3 Column2 , Because, Column1 value and Column 3 value is less than Column2
所以对于这个实现,我们将使用 colnames() 和 max.col() 函数
句法:
colnames(dataframe)[max.col(dataframe)]
这里,
- 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"