【问题标题】:How to mutate columns in place but keep same column types in R如何就地改变列但在 R 中保持相同的列类型
【发布时间】:2022-11-29 05:13:03
【问题描述】:

如果另一个数据框列为空白,我将多个数据框列设置为空白,就地突变工作正常。但是,变异列的类型已更改。如何在不更改列类型的情况下执行此操作?

从数据 1 开始:

我得到数据 2:

任何想法如何在不更改任何列类型的情况下执行此操作?也许在变异之前保存所有列类型,然后在变异之后将它们设置回去?

这是我创建 data1 并变异为 data2 的代码:

options(stringsasfactors = FALSE)
col_1_ferment <- c(452,768,856,192,905,752) #numeric type
col_1_crutch <- c('15','34','56','49','28','37') #character type
col_1_grease <- c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE) #boolean type
col_1_pump <- as.factor(c("3","6","3","2","1","2")) #factor type
indicator_col <- c(2,NA,2,1,1,2) #numeric type
data1 <- data.frame(col_1_ferment, col_1_crutch, col_1_grease, col_1_pump, indicator_col, check.rows = TRUE)

data2 <- data1 %>% mutate(dplyr::across(starts_with("col_1_"), ~ ifelse(is.na(indicator_col), "", .x)))

【问题讨论】:

    标签: r multiple-columns mutate


    【解决方案1】:

    您可以改用NA

    data2 <- data1 %>% mutate(dplyr::across(starts_with("col_1_"), ~ ifelse(is.na(indicator_col), NA, .x)))
    
    str(data2)
    
    'data.frame':   6 obs. of  5 variables:
     $ col_1_ferment: num  452 NA 856 192 905 752
     $ col_1_crutch : chr  "15" NA "56" "49" ...
     $ col_1_grease : logi  TRUE NA FALSE FALSE TRUE FALSE
     $ col_1_pump   : int  3 NA 3 2 1 2
     $ indicator_col: num  2 NA 2 1 1 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多