在不使用 list() 的情况下,在 dplyr 中将 NA 替换为零 [英] Replace NA with Zero in dplyr without using list()
问题描述
在 dplyr 中,我可以使用以下代码将 NA 替换为 0.问题是这会在我的数据框中插入一个列表,这会破坏进一步的分析.在这一点上,我什至不理解列表或原子向量或任何一个.我只想选择某些列,并将所有出现的 NA 替换为零.并保持列整数状态.
In dplyr I can replace NA with 0 using the following code. The issue is this inserts a list into my data frame which screws up further analysis down the line. I don't even understand lists or atomic vectors or any of that at this point. I just want to pick certain columns, and replace all occurrences of NA with zero. And maintain the columns integer status.
library(dplyr)
df <- tibble(x = c(1, 2, NA), y = c("a", NA, "b"), z = list(1:5, NULL, 10:20))
df
df %>% replace_na(list(x = 0, y = "unknown"))
这可行,但会将列转换为列表.如何在不将列转换为列表的情况下执行此操作?
That works but transforms the column into a list. How do I do it without transforming the column into a list?
这里是如何在基础 R 中执行此操作.但不确定如何将其转换为 mutate 语句:
And here's how to do it in base R. But not sure how to work this into a mutate statement:
df$x[is.na(df$x)] <- 0
推荐答案
您使用的是什么版本的 dplyr
?它可能是一个旧的.replace_na
函数现在似乎在 tidyr
中.这有效
What version of dplyr
are you using? It might be an old one. The replace_na
function now seems to be in tidyr
. This works
library(tidyr)
df <- tibble::tibble(x = c(1, 2, NA), y = c("a", NA, "b"), z = list(1:5, NULL, 10:20))
df %>% replace_na(list(x = 0, y = "unknown")) %>% str()
# Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 3 variables:
# $ x: num 1 2 0
# $ y: chr "a" "unknown" "b"
# $ z:List of 3
# ..$ : int 1 2 3 4 5
# ..$ : NULL
# ..$ : int 10 11 12 13 14 15 16 17 18 19 ...
我们可以看到 NA 值已被替换,列 x
和 y
仍然是原子向量.使用 tidyr_0.7.2
测试.
We can see the NA values have been replaced and the columns x
and y
are still atomic vectors. Tested with tidyr_0.7.2
.
这篇关于在不使用 list() 的情况下,在 dplyr 中将 NA 替换为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!