简体   繁体   English

满足条件的子集列

[英]Subset columns if they meet a condition

My task: 我的任务:

  • Select all columns where rows are either 0 or 1. 选择行为0或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 + CC应更改为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 . 因为这些行当前被描述为integernumber而不是factors And I assume that some ML-algorithms mix things up. 而且我假设某些机器学习算法会把事情混在一起。

One way with baseR: 使用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 dplyrmutate_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 这是在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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