r-rowSums不考虑同一个mutate语句中的recodes



我写了两个函数:

count_na_row <- function(., vars = NULL){

if(is.null(vars)){
rowSums(is.na(.))
} else {
rowSums(is.na(select(., vars)))
}

}
count_na_row_where <- function(., .fun = NULL){

if(is.null(.fun)){
warning('.fun is NULL. No function is applied. Counts NAs on all columns')
rowSums(is.na(.))
} else {
rowSums(is.na(select(., where(.fun))))
}
}

功能应用如下:

library(tidyverse)
df <- 
tibble(
var1 = c(1, 2, NA, 1, 3, NA, 1, 7),
var2 = c(NA, 3, 1, 3, NA, 9, NA, 4),
varstr = c("A", "B", "", "", 'F', 'C', 'A', "M")
)
df %>% 
mutate(
na_count = count_na_row(.),
na_count_str = count_na_row_where(., is.character)
)

我的问题是,这些函数没有考虑在同一个mutate语句中重新编码的NA值:

df %>% 
mutate(
varstr = ifelse(varstr == "", NA, varstr),
na_count = count_na_row(.),
na_count_str = count_na_row_where(., is.character),
na_count_num = count_na_row_where(., is.numeric)
)

但是,如果我在一个单独的、前面的mutate语句中重新编码,它就会起作用:

df %>%
mutate(
varstr = ifelse(varstr == "", NA, varstr)
) %>% 
mutate(
na_count = count_na_row(.),
na_count_str = count_na_row_where(., is.character),
na_count_num = count_na_row_where(., is.numeric)
)

如何调整函数,以便在同一个mutate语句中重新编码为NA值?我怀疑问题出在rowSums上。

这是按预期工作的。它与rowSums的关系不如与.运算符的关系那么大。

magittr文档中,我们可以找到:

将lhs放置在rhs中的其他位置调用

通常你会想要lhs到rhs在第一个位置以外的另一个位置呼叫。为此,您可以使用点(.(作为占位符。例如,y%>%f(x,.(是等价的到f(x,y(和z%>%f(x,y,arg=.(等价于f(x、y,arg=z( 。

这里重要的是.指的是LHS。当你这样构建你的管道时:

df %>%
mutate(x = ...,
y = rowSums(.))

LHS仍然是df,因为这是最后一个%>%之前的代码。如果你想考虑突变的x,你必须使用嵌套突变将其放入LHS中,如下所示:

df %>%
mutate(x = ...) %>%
mutate(y = rowSums(.))

最新更新