English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Il fattore viene utilizzato per memorizzare il tipo di dati di categoria diversa, ad esempio il genere umano ha maschio e femmina due categorie, per classificare l'età può essere minorenne e maggiorenne.
In R, per creare un fattore si utilizza la funzione factor(), dove il vettore è il parametro di input.
Sintassi della funzione factor():
factor(x = character(), levels, labels = levels, exclude = NA, ordered = is.ordered(x), nmax = NA)
Parameter Description:
x: vettore.
levels: specifica i valori dei livelli, se non specificato, vengono calcolati i diversi valori di x.
labels: etichette dei livelli, se non specificato, viene utilizzato il corrispondente stringa del valore di ciascun livello.
exclude: caratteri da escludere.
ordered: valore logico utilizzato per specificare se i livelli sono ordinati.
nmax: numero massimo di livelli.
Esempio di conversione di un vettore di caratteri in fattore:
x <- c("男", "女", "男", "男", "女") sex <- factor(x) print(sex) print(is.factor(sex))
The output of executing the above code is:
[1] 男 女 男 男 女 Levels: 男 女 [1] TRUE
Esempio di impostazione del livello dei fattori in c('男','女'):
x <- c("男", "女", "男", "男", "女", levels=c('男','女')) sex <- factor(x) print(sex) print(is.factor(sex))
The output of executing the above code is:
levels1 levels2 男 女 男 男 女 男 女 Levels: 男 女 [1] TRUE
Next, we use the labels parameter to add labels to each factor level, the character order of the labels parameter must be consistent with the character order of the levels parameter, for example:
sex = factor(c('f', 'm', 'f', 'f', 'm'), levels = c('f', 'm'), labels = c('female', 'male'), ordered = TRUE) print(sex)
The output of executing the above code is:
[1] female male female female male Levels: female < male
We can use the gl() function to generate factor levels, the syntax format is as follows:
gl(n, k, length = n*k, labels = seq_len(n), ordered = FALSE)
Parameter Description:
n: Set the number of levels
k: Set the number of repetitions for each level
length: Set length
labels: Set the value of level
ordered: Set whether the level is ordered, boolean value.
v <- gl(3, 4, labels = c("Google", "w3codebox", "Taobao")) print(v)
The output of executing the above code is:
[1] Google Google Google Google w3codebox w3codebox w3codebox w3codebox Taobao Taobao [11] Taobao Taobao Levels: Google w3codebox Taobao