daDoctoR/R/col_fact.R

38 lines
974 B
R
Raw Normal View History

2018-10-02 21:07:43 +02:00
#' Formatting multiple columns as factor
#'
#' Depending on dply's contains()-function.
#' @param string Columnnames containg strings.
#' @param data Dataframe
#' @param levels Levels for all selected columns
#' @param labels labels for all selected columns
#' @keywords factor
#' @export
col_fact<-function(string,data,levels=NULL,labels=NULL){
## Defining factors for columns containing string (can be vector of multiple strings), based on dplyr.
## Factoring several columns with same levels or labels, these can be provided.
2018-10-09 14:27:07 +02:00
2018-10-02 21:07:43 +02:00
require(dplyr)
d<-data
s<-string
n<-c()
2018-10-09 14:27:07 +02:00
2018-10-02 21:07:43 +02:00
for(i in 1:length(s)){
2018-10-09 14:27:07 +02:00
n<-c(n,names(dplyr::select(d,dplyr::contains(s[i]))))
2018-10-02 21:07:43 +02:00
}
if (!is.null(levels)){
for(i in 1:length(n)) {
d[,n[i]]<-factor(d[,n[i]],levels=levels)}}
2018-10-09 14:27:07 +02:00
if (!is.null(labels)){
2018-10-02 21:07:43 +02:00
for(i in 1:length(n)) {
d[,n[i]]<-factor(d[,n[i]],labels=labels)
}}
2018-10-09 14:27:07 +02:00
else
2018-10-02 21:07:43 +02:00
for(i in 1:length(n)) {
d[,n[i]]<-factor(d[,n[i]])}
2018-10-09 14:27:07 +02:00
2018-10-02 21:07:43 +02:00
return(d)
}