Home › Forums › Main Forums › R Forum › R looping and as_label() function
-
Provided that we need a macro to loop over many columns, we can define a custom function (a macro) then call it in use.
######## Define a custom function ##########
cover<- function(df, x) {mv_x<- enquo(x)
df %>%
mutate(value=<wbr>case_when( is.na(!!mv_x) | !!mv_x<0 ~ 'NA',
TRUE ~ 'real value' ) ) %>%
proc_freq(0, value) %>%
filter(value =='real value') %>%
select(value, freq, cum_freq, pct) }
#### call the custom function with a for loop ####
varlist<- raw %>% varname(1)
output <- data.frame()
num <- varlist %>% filter(type !='character')
for (x in num$var) { var <- sym(x)
#Note: rlang:sym() function is same as as.name function in base R.
print(x)
freq<- raw %>% cover(!!var) %>%
mutate(var= x ) %>%
select(var, value, freq, cum_freq, pct)
output<- output %>% bind_rows(freq) }
output %>% proc_print("Proc Print Results")We can use the mutate(var=x) to add the column name as a new column in the output data, because x is one element of a character vector.
-
However, if we want to call the custom function manually like below, and we also want to add a new column for the column name, we have to use the as_label function to achieve it.
cover<- function(df, x) {mv_x<- enquo(x)
df %>%
proc_freq(0, !!mv_x) %>%
mutate(var=as_label(mv_x)) %>%
select(value, freq, cum_freq, pct) }as_label() transforms R objects into a short, human-readable description. You can use labels to:
1) Display an object in a concise way, for example to labellise axes in a graphical plot.
2) Give default names to columns in a data frame. In this case, labelling is the first step before name repair.
Unlike as_label(), as_string() is a well defined operation that guarantees the roundtrip symbol -> string -> symbol. In general, if you don’t know for sure what kind of object you’re dealing with (a call, a symbol, an unquoted constant), use as_label() and make no assumption about the resulting string.
If you know you have a symbol and need the name of the object it refers to, use as_string(). For instance, use as_label() with objects captured with enquo() and as_string() with symbols captured with ensym().
- This reply was modified 4 years ago by Datura.
Log in to reply.