【问题标题】:List that contains some dataframes with NaN values. How to remove them?包含一些具有 NaN 值的数据帧的列表。如何删除它们?
【发布时间】:2019-06-26 03:19:08
【问题描述】:

我想从包含单行的列表数据帧中创建一个数据帧。我试图将它们绑定在一起以删除 NaN 值,但只有在没有 NaN 值的情况下才能绑定!

我得到了什么:

[[1]]
[1]          NaN 9.840158e+17

[[2]]
[1]          NaN 9.838244e+17

[[3]]
[1] 6.842105e-01 9.837743e+17

[[4]]
[1] 2.527174e+00 9.837643e+17

[[5]]
[1] 1.168269e+00 9.836988e+17

[[6]]
[1]         NaN 9.83663e+17

我想要什么:

[1]
      impact           id
6.842105e-01 9.837743e+17
2.527174e+00 9.837643e+17
1.168269e+00 9.836988e+17

我尝试了什么:

bind_rows(data, .id = "id")

Error: Argument 1 must have names

为了重现问题:

list(c(NaN, 984015782521835008), c(NaN, 983824424532144000), 
c(0.684210526315789, 983774270886236032), c(2.52717391304348, 
983764328443796992), c(1.16826923076923, 983698762760704000
), c(NaN, 983662953894435968))

关于如何解决这个问题的任何提示?

【问题讨论】:

  • 该错误与没有名称的列表有关,而不是 NaN。

标签: r dataframe na


【解决方案1】:

我们删除具有NaNlist 元素,然后删除rbind 元素

out <- do.call(rbind, lst1[!sapply(lst1, function(x) any(is.nan(x)))])
colnames(out) <- c("impact", "id")
out
#       impact           id
#[1,] 0.6842105 9.837743e+17
#[2,] 2.5271739 9.837643e+17
#[3,] 1.1682692 9.836988e+17

或者另一种选择是 rbind 元素,然后使用 na.omit

na.omit(do.call(rbind, lst1))

或者Filter

do.call(rbind, Filter(function(x) !any(is.nan(x)), lst1))

或使用discard(来自purrr

library(purrr)
discard(lst1, ~ any(is.nan(.x))) %>%
        do.call(rbind, .)

【讨论】:

    【解决方案2】:

    当您想从数据框中删除 NA 时,您可以使用函数

    数据

    DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA))
    
    na.omit(DF)
    
    print (DF)
    x  y
    1  0
    2 10
    
    na.exclude(DF)
    
    print(DF)
    x  y
    1  0
    2 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2022-12-09
      • 2020-11-23
      • 1970-01-01
      • 2018-05-08
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多