提问人:Mark Davies 提问时间:11/8/2023 最后编辑:r2evansMark Davies 更新时间:11/8/2023 访问量:39
单列replace_na错误。“replace”必须是列表,而不是数字
Error with replace_na single column. `replace` must be a list, not a number
问:
我想将一列中的所有内容替换为 .NA
0
这是我的MWE:
df = structure(list(stage = c("CKD12", "CKD12", "CKD12", "CKD12",
"CKD3a", "CKD3a"), smokes = c("Current", "Ex-smoker", "Never",
"Unknown", "Current", "Ex-smoker"), n = c(3, 4, 11, 0, NA, 6)), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
我可以用
df$n= tidyr::replace_na(df$n,0)
但是我想在一系列管道表达式中做到这一点,并尝试这样做:
df%>%replace_na(n,0)
但是得到这个错误:
Error in `replace_na()`:
! `replace` must be a list, not a function.
Run `rlang::last_trace()` to see where the error occurred.
Error in `replace_na()`:
! Arguments in `...` must be used.
x Problematic argument:
* ..1 = 0
i Did you misspell an argument name?
这个功能我做错了什么?
答:
1赞
r2evans
11/8/2023
#1
阅读文档(以“星球大战”的语气说......
看,相关的论据是:?replace_na
data: A data frame or vector.
replace: If ‘data’ is a data frame, ‘replace’ takes a named list of
values, with one value for each column that has missing
values to be replaced. Each value in ‘replace’ will be cast
to the type of the column in ‘data’ that it being used as a
replacement in.
If ‘data’ is a vector, ‘replace’ takes a single value. This
single value replaces all of the missing values in the
vector. ‘replace’ will be cast to the type of ‘data’.
在第一次调用中,第一个参数是一个向量 (),其必须是单个值(标量)。replace_na(df$n,0)
df$n
replace
但是,在第二个表达式中,第一个参数是一个框架,因此必须是一个命名列表,其中名称指示要查找和替换值的列。我们将使用 ,因为您希望在名为 的列中将值替换为 。df%>%replace_na(n,0)
data
replace
NA
list(n=0)
NA
0
n
df %>%
replace_na(list(n = 0))
# # A tibble: 6 × 3
# stage smokes n
# <chr> <chr> <dbl>
# 1 CKD12 Current 3
# 2 CKD12 Ex-smoker 4
# 3 CKD12 Never 11
# 4 CKD12 Unknown 0
# 5 CKD3a Current 0
# 6 CKD3a Ex-smoker 6
评论