labelled (version 2.0.2)

to_labelled: Convert to labelled data

Description

Convert a factor or data imported with foreign or memisc to labelled data.

Usage

to_labelled(x, ...)

# S3 method for data.frame to_labelled(x, ...)

# S3 method for list to_labelled(x, ...)

# S3 method for data.set to_labelled(x, ...)

# S3 method for importer to_labelled(x, ...)

foreign_to_labelled(x)

memisc_to_labelled(x)

# S3 method for factor to_labelled(x, labels = NULL, ...)

Arguments

x

Factor or dataset to convert to labelled data frame

...

Not used

labels

When converting a factor only: an optional named vector indicating how factor levels should be coded. If a factor level is not found in labels, it will be converted to NA.

Value

A tbl data frame or a labelled vector.

Details

to_labelled is a general wrapper calling the appropriate sub-functions.

memisc_to_labelled converts a data.set object created with memisc package to a labelled data frame.

foreign_to_labelled converts data imported with read.spss or read.dta from foreign package to a labelled data frame, i.e. using labelled class. Factors will not be converted. Therefore, you should use use.value.labels = FALSE when importing with read.spss or convert.factors = FALSE when importing with read.dta.

To convert correctly defined missing values imported with read.spss, you should have used to.data.frame = FALSE and use.missings = FALSE. If you used the option to.data.frame = TRUE, meta data describing missing values will not be attached to the import. If you used use.missings = TRUE, missing values would have been converted to NA.

So far, missing values defined in Stata are always imported as NA by read.dta and could not be retrieved by foreign_to_labelled.

See Also

labelled (foreign), read.spss (foreign), read.dta (foreign), data.set (memisc), importer (memisc), to_factor.

Examples

Run this code
# NOT RUN {
  # from foreign
  library(foreign)
  sav <- system.file("files", "electric.sav", package = "foreign")
  df <- to_labelled(read.spss(
    sav,
    to.data.frame = FALSE,
    use.value.labels = FALSE,
    use.missings = FALSE
 ))

 # from memisc
 library(memisc)
 nes1948.por <- UnZip('anes/NES1948.ZIP', 'NES1948.POR', package='memisc')
 nes1948 <- spss.portable.file(nes1948.por)
 df <- to_labelled(nes1948)
 ds <- as.data.set(nes19480)
 df <- to_labelled(ds)
# }
# NOT RUN {
# Converting factors to labelled vectors
f <- factor(c("yes", "yes", "no", "no", "don't know", "no", "yes", "don't know"))
to_labelled(f)
to_labelled(f, c("yes" = 1, "no" = 2, "don't know" = 9))
to_labelled(f, c("yes" = 1, "no" = 2))
to_labelled(f, c("yes" = "Y", "no" = "N", "don't know" = "DK"))

s1 <- labelled(c('M', 'M', 'F'), c(Male = 'M', Female = 'F'))
labels <- val_labels(s1)
f1 <- to_factor(s1)
f1

to_labelled(f1)
identical(s1, to_labelled(f1))
to_labelled(f1, labels)
identical(s1, to_labelled(f1, labels))
# }

Run the code above in your browser using DataCamp Workspace