如何获取 max() 到 return 变量名而不是 R 中变量的内容?
How to get max() to return variable names instead of contents of the variables in R?
从下面的 table 中,我有一个频率 table,虽然我能够找到最大值,但我更愿意使用变量的 "name", 所以答案是 6,而不是 8。
x <- c(1,3,6,7,2,6,7,8,8,5,1,2,3,9,5,4,1,8,3,4,3,6,8,5,8,7,4,6,6,6,6,6)
t <- table(x)
## x
## 1 2 3 4 5 6 7 8 9
## 3 2 4 3 3 8 3 5 1
max(t)
## [1] 8
我知道有一个which.max()
函数;但是,我尝试实现的代码涉及“n”个变量,因此每次代码为 运行 时我都无法写出每个变量名。
我们可以使用 which.max
到 return 第一个最大值的索引并使用它来获得 names
names(which.max(t))
如果 max
值有关系,用 ==
创建逻辑 vector
,用 which
获取所有位置索引并提取 names
names(which(t == max(t)))
您正在尝试计算众数,即向量中出现频率最高的值。
我们可以使用here
中的函数
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
Mode(x)
#[1] 6
从下面的 table 中,我有一个频率 table,虽然我能够找到最大值,但我更愿意使用变量的 "name", 所以答案是 6,而不是 8。
x <- c(1,3,6,7,2,6,7,8,8,5,1,2,3,9,5,4,1,8,3,4,3,6,8,5,8,7,4,6,6,6,6,6)
t <- table(x)
## x
## 1 2 3 4 5 6 7 8 9
## 3 2 4 3 3 8 3 5 1
max(t)
## [1] 8
我知道有一个which.max()
函数;但是,我尝试实现的代码涉及“n”个变量,因此每次代码为 运行 时我都无法写出每个变量名。
我们可以使用 which.max
到 return 第一个最大值的索引并使用它来获得 names
names(which.max(t))
如果 max
值有关系,用 ==
创建逻辑 vector
,用 which
获取所有位置索引并提取 names
names(which(t == max(t)))
您正在尝试计算众数,即向量中出现频率最高的值。
我们可以使用here
中的函数Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
Mode(x)
#[1] 6