r语言 - 从 head() 函数中提取最大值和最小值?



我正在分析向量的片段,为此我需要提取它们的最大值。

执行此操作的正常方法是使用max(vector, na.rm = TRUE). 但是,在某些段中,不会显示向量的实际最大值,因此它给出了该段向量的最大值。

为此,我想从 head(( 函数中提取最大值,如下所示:

library(expss)
nps = c(-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 1)
var_lab(nps) = "Net promoter score"
val_lab(nps) = num_lab("-1 Detractors
0 Neutralists    
1 Promoters")
head(nps)
Output:
Detractors  -1  Detractors      
Neutralists  0  Neutralists     
Promoters    1  Promoters

在这种情况下,我想从中间列中提取"1"。我尝试将 head(( 的输出转换为数据帧,但这只给出了向量的前 5 个值。有什么想法吗?

如果所有值都有标签,那么最简单的方法是从值标签中提取最大值:

library(expss)
vec = structure(c(6, 5, 5, 4, 5, 5), labels = c(`Missing; Unknown` = -5, `Not asked in survey` = -4, `Not applicable` = -3, `No answer` = -2, `Don´t know` = -1, Left = 1, `2` = 2, `3` = 3, `4` = 4, `5` = 5, `6` = 6, `7` = 7, `8` = 8, `9` = 9, Right = 10), class = "labelled")
max(val_lab(vec))
# 10

如果您的向量有一些没有标签的值,那么您可以使用unique

nps = c(-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 1)
var_lab(nps) = "Net promoter score"
# no label for 1
val_lab(nps) = num_lab("-1 Detractors
0 Neutralists")
# nmax = 1 indicate that unique will return values from vector and values from labels 
max(unique(nps, nmax = 1))
nps = c(-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 1)
var_lab(nps) = "Net promoter score"
val_lab(nps) = num_lab("-1 Detractors
0 Neutralists
1 Promoters")
max(stack(attr(nps, 'labels'))$values)
[1] 1

此解决方案源自此处的答案:提取标记数据的值和标签

最新更新