當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R haven labelled 創建一個標記向量。

帶標簽向量是其他統計環境中的常見數據結構,允許您將文本標簽分配給特定值。此類可以將此類標記向量導入到 R 中,而不會損失保真度。這個類提供了一些方法,因為我希望您在導入後很快就會強製使用標準 R 類(例如 factor() )。

用法

labelled(x = double(), labels = NULL, label = NULL)

is.labelled(x)

參數

x

要標記的向量。必須是數字(整數或雙精度)或字符。

labels

命名向量或 NULL 。該向量的類型應與 x 相同。與因子不同,標簽不需要詳盡無遺:隻可以標記一小部分值。

label

向量的簡短、人類可讀的說明。

例子

s1 <- labelled(c("M", "M", "F"), c(Male = "M", Female = "F"))
s2 <- labelled(c(1, 1, 2), c(Male = 1, Female = 2))
s3 <- labelled(
  c(1, 1, 2),
  c(Male = 1, Female = 2),
  label = "Assigned sex at birth"
)

# Unfortunately it's not possible to make as.factor work for labelled objects
# so instead use as_factor. This works for all types of labelled vectors.
as_factor(s1)
#> [1] Male   Male   Female
#> Levels: Female Male
as_factor(s1, levels = "values")
#> [1] M M F
#> Levels: M F
as_factor(s2)
#> [1] Male   Male   Female
#> Levels: Male Female

# Other statistical software supports multiple types of missing values
s3 <- labelled(
  c("M", "M", "F", "X", "N/A"),
  c(Male = "M", Female = "F", Refused = "X", "Not applicable" = "N/A")
)
s3
#> <labelled<character>[5]>
#> [1] M   M   F   X   N/A
#> 
#> Labels:
#>  value          label
#>      M           Male
#>      F         Female
#>      X        Refused
#>    N/A Not applicable
as_factor(s3)
#> [1] Male           Male           Female         Refused       
#> [5] Not applicable
#> Levels: Female Male Not applicable Refused

# Often when you have a partially labelled numeric vector, labelled values
# are special types of missing. Use zap_labels to replace labels with missing
# values
x <- labelled(c(1, 2, 1, 2, 10, 9), c(Unknown = 9, Refused = 10))
zap_labels(x)
#> [1]  1  2  1  2 10  9
源代碼:R/labelled.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Create a labelled vector.。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。