简体   繁体   中英

Subset columns if they meet a condition

My task:

  • Select all columns where rows are either 0 or 1.
  • Change the class all of these columns to factorial (as they are binary).

In the below case, CA + CC should change to factorial .

CA = c(1,0,1,0,1)
CB = c(1,12,21,0,7)
CC = c(1,0,1,0,1)
mydf = data.frame(CA, CB, CC)
str(mydf)
    'data.frame':   5 obs. of  3 variables:
     $ CA: num  1 0 1 0 1
     $ CB: num  1 12 21 0 7
     $ CC: num  1 0 1 0 1

Why? Because these rows are currently depicted as integer and number instead of factors . And I assume that some ML-algorithms mix things up.

One way with baseR:

#if all the values in a column are either 0 or 1 convert to factor
mydf[] <- lapply(mydf, function(x) {
  if(all(x %in% 0:1)) {
    as.factor(x)
  } else {
    x
  }
})

Out:

str(mydf)
#'data.frame':  5 obs. of  3 variables:
# $ CA: Factor w/ 2 levels "0","1": 2 1 2 1 2
# $ CB: num  1 12 21 0 7
# $ CC: Factor w/ 2 levels "0","1": 2 1 2 1 2**

Another approach with dplyr 's mutate_if

library(dplyr) 
is_one_zero <- function(x) {

  res <- all(unique(x) %in% c(1, 0))

  return(res)
}

out <- mydf %>% 
  mutate_if(is_one_zero, as.factor) 

str(out)
#'data.frame':  5 obs. of  3 variables:
# $ CA: Factor w/ 2 levels "0","1": 2 1 2 1 2
# $ CB: num  1 12 21 0 7
# $ CC: Factor w/ 2 levels "0","1": 2 1 2 1 2

Just another way to do it in base R

cols <- colSums(mydf == 0 | mydf == 1) == nrow(mydf)
mydf[cols] <- lapply(mydf[cols], as.factor)

str(mydf)
#'data.frame':  5 obs. of  3 variables:
# $ CA: Factor w/ 2 levels "0","1": 2 1 2 1 2
# $ CB: num  1 12 21 0 7
# $ CC: Factor w/ 2 levels "0","1": 2 1 2 1 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM