當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R dtplyr replace_na.dtplyr_step 將 NA 替換為指定值

這是 tidyr replace_na() 泛型的方法。它被翻譯為 data.table::fcoalesce()

請注意,與 tidyr::replace_na() 不同,data.table::fcoalesce() 無法替換列表中的 NULL 值。

用法

# S3 method for dtplyr_step
replace_na(data, replace = list())

參數

data

一個lazy_dt()

replace

如果 data 是 DataFrame ,則 replace 采用命名的值列表,其中每列有一個值需要替換缺失值。 replace 中的每個值都將轉換為 data 中用作替換的列的類型。

如果data 是向量,則replace 采用單個值。該單個值替換向量中的所有缺失值。 replace 將轉換為 data 的類型。

例子

library(tidyr)

# Replace NAs in a data frame
dt <- lazy_dt(tibble(x = c(1, 2, NA), y = c("a", NA, "b")))
dt %>% replace_na(list(x = 0, y = "unknown"))
#> Source: local data table [3 x 2]
#> Call:   copy(`_DT35`)[, `:=`(x = fcoalesce(x, 0), y = fcoalesce(y, "unknown"))]
#> 
#>       x y      
#>   <dbl> <chr>  
#> 1     1 a      
#> 2     2 unknown
#> 3     0 b      
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

# Replace NAs using `dplyr::mutate()`
dt %>% dplyr::mutate(x = replace_na(x, 0))
#> Source: local data table [3 x 2]
#> Call:   copy(`_DT35`)[, `:=`(x = fcoalesce(x, 0))]
#> 
#>       x y    
#>   <dbl> <chr>
#> 1     1 a    
#> 2     2 NA   
#> 3     0 b    
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results
源代碼:R/replace_na.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Replace NAs with specified values。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。