1

I imported a .txt file using read_fwf and it seems like col_factor does not support labels as its arguments. I was wondering if there are ways on how you can add labels to specific values in a tibble.

col_types = cols("Income Category" = col_factor(levels = c("01", "02", "03), labels = c("low", "medium", "high"))

I'm fairly new to R so I would be grateful if anyone can answer my question!

AJV7
  • 11
  • 4

1 Answers1

1

Perhaps this helps:

library(tibble)
library(expss)


# Sample data
nn = 99 # total sample size

# create a tibble data frame with single column named IncomeCategory and
# attribute 1, 2, and 3 evenly (just for the example)
tib <- tibble(IncomeCategory = rep(c(1, 2, 3), each = nn/3))

# Attribute labels "low", "medium", and "high" to values 1, 2, and 3 respectively
val_lab(tib$IncomeCategory) = num_lab("1 low
                                       2 medium
                                       3 high")

Structure output shows values are labelled:

> str(tib)
tibble [99 × 1] (S3: tbl_df/tbl/data.frame)
 $ IncomeCategory:Class 'labelled' num [1:99] 1 1 1 1 1 1 1 1 1 1 ...
   .. .. VALUE LABELS [1:3]: 1=low, 2=medium, 3=high 

Sources:

pdeli
  • 436
  • 3
  • 13