【问题标题】:Recoding Values For a Single Column in R (includes NULL values)为 R 中的单个列重新编码值(包括 NULL 值)
【发布时间】:2019-04-24 16:13:37
【问题描述】:

我有一个名为 data.comp 的数据框,其中有一个名为 RELAFFIL 的列。列内的值范围从 22 到 107,但也有许多 NULL 值。我想将所有 NULL 值的值重新编码为 0,对于所有其他情况,我想将值重新编码为 1。我尝试了多种方法,但都没有奏效,仅供参考,我在下面列出了我尝试过的方法。另外仅供参考,我加载了以下软件包:dplyr、readr 和 car。

data.comp$RELAFFIL <- with(data.comp, ifelse(is.null(data.comp$RELAFFIL), 0, 1))

data.comp$RELAFFIL[is.null(data.comp$RELAFFIL)] <- 0

data.comp$RELAFFIL[is.finite(data.comp$RELAFFIL)] <- 1

car::recode(data.comp$RELAFFIL, "NULL = 0; else = 1")

data.comp$RELAFFIL <- data.comp$RELAFFIL %>% base::ifelse(is.null(data.comp$RELAFFIL), 0, 1)

【问题讨论】:

  • 欢迎来到 StackOverflow!请阅读有关how to ask a good question 的信息以及如何提供reproducible example。这将使其他人更容易帮助您。
  • data.comp$RELAFFIL &lt;- ifelse(is.null(data.comp$RELAFFIL), 0, 1) 不起作用吗?
  • 不,它将所有值(包括 NULL)重新编码为 1。

标签: r null rstudio


【解决方案1】:

对此的基本 R 解决方案是将提及 NA 字符串的文件导入为空。下面提供代码

data.comp <- read.csv("your csv file",stringsAsFactors = F,na.strings = c("null"))
data.comp[is.na(data.comp)] <- 0

data.comp$RELAFFI_new <-ifelse(data.comp$RELAFFIL == 0,0,1)

这将提供您所需的输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多