【问题标题】:R data table replace NULL with 0 never changes valueR数据表用0替换NULL永远不会改变值
【发布时间】:2019-05-18 16:37:54
【问题描述】:

它看起来真的很简单,但似乎根本不起作用..我的要求只是用 0 替换 NULL 值。我没有尝试lapply 和其他多行解决方案,因为我觉得有一个简单的解决方案。还是我错了?

下面是根据 Hive 查询的输出创建的数据表。输出是一个制表符分隔的字符串 (NULL\tNULL)。所以我猜NULL是一个字符串。使用以下代码将其转换为数据表

  df <- read.table(text=ret_text, sep = "\t") #data frame
  dt=as.data.table(df) 

以下是数据

> class(ret_data)
[1] "data.table" "data.frame"

> ret_data
     V1   V2
1: NULL NULL

dput 输出

> dput(ret_data)
structure(list(V1 = structure(1L, .Label = "NULL", class = "factor"), 
    V2 = structure(1L, .Label = "NULL", class = "factor")), .Names = c("V1", 
"V2"), class = c("data.table", "data.frame"), row.names = c(NA, 
-1L), .internal.selfref = <pointer: 0x3527fd8>)

以下是我尝试使用不同帖子中的回复

> ret_data[is.na(ret_data)] <- 0
> ret_data
     V1   V2
1: NULL NULL
> ret_data[is.null(ret_data)] <- 0
> ret_data
     V1   V2
1: NULL NULL
> ret_data[ret_data==NULL] <- 0

矩阵错误(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr, : 'dimnames' [2] 的长度不等于数组范围 另外:警告信息: 1:在 is.na(e2) 中:is.na() 应用于“NULL”类型的非(列表或向量) 2:在 is.na(e2) 中:is.na() 应用于“NULL”类型的非(列表或向量)

> ret_data2 <- replace(ret_data,is.na(ret_data),0)
> ret_data2
     V1   V2
1: NULL NULL
> ret_data2 <- replace(ret_data,ret_data=="NULL",0)
> ret_data2
   V1 V2
1: NA NA
> ret_data[ret_data=="NULL"] <- 0

警告信息: 1:在[&lt;-.factor(*tmp*, thisvar, value = 0) 中: 无效因子水平,NA 生成 2:在[&lt;-.factor(*tmp*, thisvar, value = 0) 中: 无效因子水平,NA生成

> ret_data
   V1 V2
1: NA NA

【问题讨论】:

  • 你能把dt或ret_data的dput发一下吗?
  • @docendodiscimus 编辑帖子添加dput
  • 你的问题可能是ret_data永远不是NULL,它是一个数据表,有两列,其中包含NULL的值
  • @ira 是的,数据表在 2 个单元格中包含 2 个 NULL 值
  • 如果将列转换为字符然后与"NULL" 进行比较会怎样?例如as.character(ret_data[, V1]) == "NULL" ?

标签: r data.table


【解决方案1】:

除非dput 以某种方式神奇地歪曲了您的数据结构,否则这应该对您有用:

# load data table library
library(data.table)
# construct the sample dataset
ret_data <- structure(list(V1 = structure(1L, .Label = "NULL", class = "factor"), 
               V2 = structure(1L, .Label = "NULL", class = "factor")),
               .Names = c("V1", "V2"),
               class = c("data.table", "data.frame"), row.names = c(NA, -1L))

# choose columns to be altered
# you might also want to change just some of the columns
cols <- colnames(ret_data)
# for each of the columns, perform an operation
for (j in cols) {set(ret_data, j = j, value = ifelse(as.character(ret_data[[j]]) == "NULL", 0, 1))}

【讨论】:

    【解决方案2】:

    目前NULL 不是NULL 而是factor。将其转换为字符并按您的意愿继续。

     df<-df %>% 
      mutate_if(is.factor,as.character) %>% 
      str_replace_all("NULL","0")
    

    如果您愿意,可以将其设为numeric

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多