foo()
is made to lowercase all character columns of a dataframe except=
the ones whose names are provided by the user.
I wonder why when I provide except="study"
, foo
incorrectly lowercases the column study
in the data
?
Reproducible code and desired output are below.
m="
study cap back
AA L 1
BB F 2
CC H 8"
data <- read.table(text=m,h=T)
foo <- function(X, except = NULL){
y <- sapply(setdiff(names(X), except), function(x) is.character(as.vector(X[[x]])))
X[y] <- lapply(X[y], tolower)
return(X)
}
#=== EXAMPLE OF USE:
foo(data, except = c("study"))
Desired_output=
"
study cap back
AA l 1
BB f 2
CC h 8"
CodePudding user response:
Here are two ways to achieve this -
Base R -
foo <- function(X, except = NULL){
y <- names(Filter(is.character, X[setdiff(names(X), except)]))
X[y] <- lapply(X[y], tolower)
return(X)
}
foo(data, except = c("study"))
# study cap back
#1 AA l 1
#2 BB f 2
#3 CC h 8
Using dplyr
-
library(dplyr)
foo <- function(X, except = NULL){
X %>%
mutate(across(where(is.character) &
all_of(setdiff(names(X), except)), tolower))
}
foo(data, except = c("study"))
CodePudding user response:
data <- data.frame(
Study = c("AA", "BB", "CC"),
Cap = c("L", "F", "H"),
Back = c(1, 2, 8))
foo <- function(X, except){
targs <- setdiff(names(X), except)
colnames(X)[which(names(X) %in% targs)] <- tolower(targs)
return(X)
}
except <- "Study"
foo(data, except)
#> Study cap back
#> 1 AA L 1
#> 2 BB F 2
#> 3 CC H 8
Created on 2021-12-10 by the reprex package (v2.0.1)