We can put labels to the columns of a df with label, for example
df <-data.frame(col1=c(1,2,3), col2=c(1,2,3),col3=c(1,2,3))
library(Hmisc)
label(df$col1)<-"ID"
label(df$col2)<-"Ventas"
label(df$col3)<-"Compras"
How can I list them with a loop like...
label(df$col1)<-"1"
label(df$col2)<-"2"
label(df$col3)<-"3"
The simplest is to iterate through each column and add the index:
Or failing that, using base R to dispense with
Hmisc
:A functional alternative would be
Use
map2_df()
to iterate over two lists: the list of columns (df) and the list of labels. As it is_df
going to return us a data.frame and not a simple list.The function I use has to take at least two arguments, one for
.x
and one for.y
. In this case I useattr<-
, which is a version ofattr
with assignment: instead of making a subset of the attributes, it directly assigns a value to them. This way I don't have to make explicit use of the binary operator<-
, which would be more complicated within a call tomap
.In R there are several functions
función<-
that have this behavior. In addition toattr<-
thisnames<-
, to name the elements of a list or vector,colnames<-
,levels<-
,is.na<-
and others. They are very useful for functional programming, they avoid us having to declare the function and use{}
to delimit it and use inside<-
.Wearing
You get a list of all functions with that pattern within the base package.