从 head() 函数中提取最大值和最小值?

Extract maxmimum and minimum from head() function?

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

通常的做法是使用 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 个值。有什么想法吗?

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

此解决方案源自此处的答案:

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

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))