简体   繁体   English

表和 $freq 函数如何在 R 中工作

[英]How does the table and $freq function work in R

I want a function for the mode of a vector.我想要一个向量模式的函数。 Abhiroop Sarkar's answer to This question works, but I want to understand why. Abhiroop Sarkar 对This question的回答有效,但我想了解原因。

Here is the code这是代码

Mode <- function(x){

y <- data.frame(table(x))
y[y$Freq == max(y$Freq),1]
}

1) Wy do we need to put the table in a data frame, 1)我们需要将表格放入数据框中,

2) in this line 2)在这一行

 y[y$Freq == max(y$Freq),1]

what does the y$Freq do? y$Freq 有什么作用? is frequency a default columns in the table?频率是表中的默认列吗?

When we convert a table output to data.frame , it creates a two column data.frame当我们将table输出转换为data.frame ,它会创建一个两列data.frame

set.seed(24)
v1 <- table(sample(1:5, 100, replace  = TRUE))
y <- data.frame(v1)
y
#  Var1 Freq
#1    1   19
#2    2   24
#3    3   22
#4    4   16
#5    5   19

The first column 'Var1' is the names of the frequency output from table and the 'Freq' is the actual frequency of those names第一列“Var1”是table输出频率的names ,“Freq”是这些names的实际频率

y[y$Freq == max(y$Freq), 1]
#[1] 2
#Levels: 1 2 3 4 5

Now, we are subsetting the first column 'Var1' based on the max value of 'Freq', and it returns a vector because of the drop = TRUE in [ when there is a single column现在,我们根据 'Freq' 的max对第一列 'Var1' 进行子集化,它返回一个vector因为当有单列时[中的drop = TRUE

If we want to return a data.frame with single, add drop = FALSE at the end如果我们想返回一个单一的data.frame ,在最后添加drop = FALSE

y[y$Freq == max(y$Freq), 1, drop = FALSE]
#   Var1
#2    2

Regarding the default name Freq , it is created from the as.data.frame.table method关于默认名称Freq ,它是从as.data.frame.table方法创建的

as.data.frame.table
function (x, row.names = NULL, ..., responseName = "Freq", stringsAsFactors = TRUE, 
    sep = "", base = list(LETTERS)) 
{
    ex <- quote(data.frame(do.call("expand.grid", c(dimnames(provideDimnames(x, 
        sep = sep, base = base)), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = stringsAsFactors)), 
        Freq = c(x), row.names = row.names))
    names(ex)[3L] <- responseName
    eval(ex)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM