-
Notifications
You must be signed in to change notification settings - Fork 2
/
convertCase.R
67 lines (61 loc) · 2.37 KB
/
convertCase.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
####
#############################################################################
#' Modify upper and lower case for strings.
#'
#' Convert a character vector, all character variables in a \code{data.frame} or selected variables in a \code{GADSdat} to
#' upper (\code{"uppper"}), lower (\code{"lower"}), or first letter upper and everything else lower case (\code{"upperFirst"}).
#'
#'@param x A character vector, \code{data.frame}, or \code{GADSdat}.
#'@param case Character vector of length 1. What case should the strings be converted to? Available options are
#'\code{"lower"}, \code{"upper"}, or \code{"upperFirst"}.
#'@param ... further arguments passed to or from other methods.
#'@param vars Character vector. What variables in the \code{GADSdat} should the conversion be applied to?
#'
#'@return Returns the converted object.
#'
#'@examples
#' # for character
#' convertCase(c("Hi", "HEllo", "greaT"), case = "upperFirst")
#'
#' # for GADSdat
#' input_g <- import_DF(data.frame(v1 = 1:3, v2 = c("Hi", "HEllo", "greaT"),
#' stringsAsFactors = FALSE))
#' convertCase(input_g, case = "upperFirst", vars = "v2")
#'
#'
#'@export
convertCase <- function(x, case = c("lower", "upper", "upperFirst"), ...){
UseMethod("convertCase")
}
#'@export
convertCase.character <- function(x, case = c("lower", "upper", "upperFirst"), ...){
case <- match.arg(case)
if(identical(case, "lower")) return(tolower(x))
if(identical(case, "upper")) return(toupper(x))
if(identical(case, "upperFirst")) {
x2 <- tolower(x)
substr(x2, 1, 1) <- toupper(substr(x2, 1, 1))
return(x2)
}
}
#'@export
convertCase.data.frame <- function(x, case = c("lower", "upper", "upperFirst"), ...){
# only transform character variables
which_character <- which(sapply(x, is.character))
for(i in which_character) {
x[[i]] <- convertCase(x[[i]])
}
x
}
#' @describeIn convertCase convert case for \code{GADSdats}
#'@export
convertCase.GADSdat <- function(x, case = c("lower", "upper", "upperFirst"), vars, ...){
check_GADSdat(x)
if(!is.character(vars) && length(vars) > 0) stop("vars needs to be a character vector of at least length 1.")
check_vars_in_GADSdat(x, vars = vars)
for(var_nam in vars) {
if(!is.character(x$dat[[var_nam]])) stop(var_nam, " is not a character variable and can not be case converted.")
x$dat[[var_nam]] <- convertCase(x$dat[[var_nam]], case = case)
}
x
}