R语言 数据框架中查找最大值的索引
在这篇文章中,我们将看到如何在R编程语言中从一个数据框架中找到最大值的索引
我们可以使用 which.max() 函数找到数据框中的最大值索引。
语法
which.max(dataframe_namecolumnname)
““用于访问数据框架的特定列。
下面给出了各种实现,描述了各种数据类型和情况,以帮助你更好地理解。
例1 :
# vector 1
data1=c("sravan","bobby","pinkey","rohith","gnanesh")
# vector 2
data2=c(98,78,79,97,89)
# creating a dataframe with names and marks
# using above vectors
final <- data.frame(names=data1,marks=data2)
print(final)
# display the maximum value index in 2 nd column
# (marks column) in a dataframe
print(paste("highest index is : ",which.max(final$marks)))
输出
如果有一个以上的最大值,那么它将返回第一个被重复的数字的索引。
例2 :
# vector 1
data1=c("sravan","bobby","pinkey","rohith",
"gnanesh",'divya',"satwik","chandu")
# vector 2
data2=c(98,78,79,97,89,89,99,99)
# creating a dataframe with names and marks
# using above vectors
final <- data.frame(names=data1,marks=data2)
print(final)
print(paste("highest index is : ",which.max(final$marks)))
输出
如果数据是字符类型的,它将使用ASCII值找到最大值。
例3 :
# vector 1
data1=c("sravan","bobby","pinkey","rohith",
"gnanesh",'divya',"satwik","zhandu")
# vector 2
data2=c(98,78,79,97,89,89,99,99)
# creating a dataframe with names and marks
# using above vectors
final <- data.frame(names=data1,marks=data2)
print(final)
# display maximum value index for character values
print(paste("highest index is : ",which.max(final$names)))
输出
例4 :
# vector 1 that contains NA values as characters
data1=c(NA,"sravan",NA,NA,NA)
# vector 2 contains all data
data2=c(102,98,98,102,102)
# creating a dataframe with names and marks
# using above vectors
final <- data.frame(names=data1,marks=data2)
print(final)
# display maximum value index for character values
print(paste("highest index is : ",which.max(finalnames)))
# display maximum value index for marks values
print(paste("highest index is : ",which.max(finalmarks)))
输出
如果包含所有数值的行是相同的,那么所有数值都是高的。所以它将返回第一个元素的索引。
例5 :
# vector contains all same data
data2=c(102,102,102,102,102)
# creating a dataframe marks using above vector
final <- data.frame(marks=data2)
print(final)
# display maximum value index for marks values
print(paste("highest index is : ",which.max(final$marks)))
输出
如果数据包含NA值,那么它将返回空值。
例6 :
# vector contains all NA's
data2=c(NA,NA)
# creating a dataframe marks using
# above vector
final <- data.frame(marks=data2)
print(final)
# display maximum value index for marks values
print(paste("highest index is : ",which.max(final$marks)))
输出