即使data.frame为空,如何安全地替换data.frame中的值? [英] How to safely replace values in data.frame even when data.frame is empty?
问题描述
我在编写安全的代码来处理R中的数据框时遇到麻烦。我遇到的问题是 df [...] < - (...)
对于没有行的数据框架(除其他外)容易受损。
I'm having trouble writing safe code to manipulate data frames in R. The problem I'm having is that df[...] <- (...)
is vulnerable to the data.frame having no rows (among other things!).
示例1:
df <- data.frame(a = 1:2, b = c(NA, 5))
df[is.na(df$b), 'b'] <- 0
我想要的 - 用0替换NA。
Does what I want - replaces NA with 0.
示例2:
df.empty <- data.frame(a = character(), b = character())
df.empty[is.na(df.empty$b), 'b'] <- 0
df.empty[is.na(df.empty$b), 'b', drop = F] <- 0
要变异示例2中的数据帧会导致错误(替换有1行,数据为0;或'未使用参数(drop = F))。
Both attempts to mutate the data frame in Example 2 result in an error (either replacement has 1 row, data has 0; or 'unused argument (drop = F)).
I发现这非常烦人。
如何根据数据框架中的任意(向量)标准,使普遍突破列。 ,而不必手动检查所有可能的条件,如NA,NULL,没有行,由于没有行而强制向量,等等?
How do I universally mutate a column based on arbitrary (vector) criterion in a data.frame, without having to manually check for all possible conditions like NA, NULL, no rows, coercion to vector because of no rows, etc.?
推荐答案
可能使用 dplyr
?
这个例子,结合 mutate()
和 ifelse()
,似乎实现了你想要。
This example, combining mutate()
and ifelse()
, seems to achieve what you want.
df.empty <- df.empty %>%
mutate(b = ifelse(is.na(b), 0, b))
这篇关于即使data.frame为空,如何安全地替换data.frame中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!