# create a data set
df <- mtcars
# variable names and their labels
names_labs_vec <- c(
"mpg" = "Miles/(US) gallon",
"cyl" = "Number of cylinders",
"disp" = "Displacement (cu.in.)",
"hp" = "Gross horsepower",
"drat" = "Rear axle ratio",
"wt" = "Weight (1000 lbs)",
"qsec" = "1/4 mile time",
"vs" = "Engine (0 = V-shaped, 1 = straight)",
"am" = "Transmission (0 = automatic, 1 = manual)",
"gear" = "Number of forward gears",
"carb" = "Number of carburetors"
)
# assign variable labels
df <- add_name_labs(df,
vars = names(names_labs_vec),
labs = names_labs_vec
)
# see what we have
get_name_labs(df)
# use these
df_labs_as_names <- use_name_labs(df)
head(df_labs_as_names)[1:3] # these are verbose, so, only show first three
head(df)[1:3]
# now revert back
df_names_as_before <- use_var_names(df_labs_as_names)
head(df_names_as_before)[1:3] # indeed, they are as before
identical(head(df), head(df_names_as_before))
# strip name label meta-data information from df
# NOT same as use_var_names(), which preserves the info but "turns it off"
# this strips the name labels meta-data from df altogether
df <- drop_name_labs(df)
# see what we have
get_name_labs(df) # they're gone
# alternative syntax (if you have a named vector like names_labs_vec)
# assign variable name labels
df <- add_name_labs(df,
name.labs = c(
"mpg" = "Miles/(US) gallon",
"cyl" = "Number of cylinders",
"disp" = "Displacement (cu.in.)",
"hp" = "Gross horsepower",
"drat" = "Rear axle ratio",
"wt" = "Weight (1000 lbs)",
"qsec" = "1/4 mile time",
"vs" = "Engine (0 = V-shaped, 1 = straight)",
"am" = "Transmission (0 = automatic, 1 = manual)",
"gear" = "Number of forward gears",
"carb" = "Number of carburetors"
)
)
# replace two variable name labels, keeping the others
df <- add_name_labs(df,
name.labs = c(
"disp" = toupper("displacement"),
"mpg" = toupper("miles per gallon")
)
)
attributes(df) # show all attributes
get_name_labs(df) # show only the variable name labels
get_name_labs(df, var = c("disp", "mpg"))
# again, strip name label meta-data information from df
# NOT same as use_var_names(), which preserves the info but "turns it off"
df <- drop_name_labs(df)
# see what we have
get_name_labs(df) # they're gone
# alternative syntax to add name labels
df <- add_name_labs(df,
vars = c("carb", "am"),
labs = c("how many carburetors?", "automatic or stick?")
)
# see what we have
get_name_labs(df) # they're back! (and placeholders for others)
# add another
df <- add_name_labs(df,
vars = c("mpg"),
labs = c("miles per gallon, of course")
)
# see what we have
get_name_labs(df) # it's been added, and others preserved
head(use_name_labs(df)[c(1, 9, 11)]) # verbose, but they're there
Run the code above in your browser using DataLab