我有一个类似于this的问题,但是我的数据集有点大:50列,其中1列作为UID,其他列带有
TRUE
或NA
,我想将所有NA
更改为FALSE
,但我不想使用显式循环。
plyr
能做到吗?谢谢。
感谢您的快速回复,但是如果我的数据集如下所示怎么办:
df <- data.frame(
id = c(rep(1:19),NA),
x1 = sample(c(NA,TRUE), 20, replace = TRUE),
x2 = sample(c(NA,TRUE), 20, replace = TRUE)
)
我只想处理
X1
和X2
,这怎么办?
如果你想做变量子集的替换,你仍然可以使用
is.na(*) <-
技巧,如下:
df[c("x1", "x2")][is.na(df[c("x1", "x2")])] <- FALSE
IMO 使用临时变量使逻辑更容易理解:
vars.to.replace <- c("x1", "x2")
df2 <- df[vars.to.replace]
df2[is.na(df2)] <- FALSE
df[vars.to.replace] <- df2
tidyr::replace_na
出色的功能。
df %>%
replace_na(list(x1 = FALSE, x2 = FALSE))
这是一个很好的快速修复。唯一的技巧是列出要更改的列。
试试这个代码:
df <- data.frame(
id = c(rep(1:19), NA),
x1 = sample(c(NA, TRUE), 20, replace = TRUE),
x2 = sample(c(NA, TRUE), 20, replace = TRUE)
)
replace(df, is.na(df), FALSE)
更新另一个解决方案。
df2 <- df <- data.frame(
id = c(rep(1:19), NA),
x1 = sample(c(NA, TRUE), 20, replace = TRUE),
x2 = sample(c(NA, TRUE), 20, replace = TRUE)
)
df2[names(df) == "id"] <- FALSE
df2[names(df) != "id"] <- TRUE
replace(df, is.na(df) & df2, FALSE)
可以使用
NAToUnknown
包中的gdata
功能
df[,c('x1', 'x2')] = gdata::NAToUnknown(df[,c('x1', 'x2')], unknown = 'FALSE')
用
dplyr
你也可以做
df %>% mutate_each(funs(replace(., is.na(.), F)), x1, x2)
与 just 使用
replace()
相比,它的可读性稍差一些,但更通用,因为它允许选择要转换的列。如果您想在某些列中保留 NA 但又想摆脱其他列中的 NA,则此解决方案尤其适用。
一个选择是使用一个
for
循环。
for(i in c("x1", "x2")) df[[i]][is.na(df[[i]])] <- FALSE
基准
set.seed(42)
df <- data.frame(
id = c(rep(1:19),NA),
x1 = sample(c(NA,TRUE), 20, replace = TRUE),
x2 = sample(c(NA,TRUE), 20, replace = TRUE)
)
bench::mark(check=FALSE,
"Holger Brandl" = local(dplyr::mutate_each(df, dplyr::funs(replace(., is.na(.), F)), x1, x2)),
"mtelesha" = local(df <- tidyr::replace_na(df, list(x1 = FALSE, x2 = FALSE))),
Ramnath = local(df[,c('x1', 'x2')] <- gdata::NAToUnknown(df[,c('x1', 'x2')], unknown = 'FALSE')),
"Hong Ooi" = local(df[c("x1", "x2")][is.na(df[c("x1", "x2")])] <- FALSE),
GKi = local(for(i in c("x1", "x2")) df[[i]][is.na(df[[i]])] <- FALSE) )
# expression min median `itr/sec` mem_al…¹ gc/se…² n_itr n_gc total…³
# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:by> <dbl> <int> <dbl> <bch:t>
#1 Holger Brandl 16.93ms 17.33ms 57.6 34.43KB 19.2 21 7 365ms
#2 mtelesha 3.94ms 4.39ms 226. 8.15KB 13.1 103 6 456ms
#3 Ramnath 400.28µs 415.44µs 2381. 1.55KB 16.7 1142 8 480ms
#4 Hong Ooi 196.87µs 206.72µs 4755. 488B 18.8 2276 9 479ms
#5 GKi 61.8µs 66.16µs 14808. 280B 20.9 7076 10 478ms
for
-loop 比第二个 Hong Ooi 快大约 3 倍,并且使用最少的内存量。