gpt4 book ai didi

用 R 中的数字和字符值替换数字列的 NA

转载 作者:行者123 更新时间:2023-12-05 01:53:07 26 4
gpt4 key购买 nike

我有一个包含多列的数据框 df。
其中两个(列 AGE 和 SALARY)是 double 类型。
我想用 0 和
替换 AGE 列的缺失值“未找到”的 SALARY 列缺失值。

最有效的方法是什么?

replace_na(df, list(AGE=0, SALARY="not found"))

我收到错误:

Error in `stop_vctrs()`:
! Can't convert `replace$SALARY` <character> to match type of `data$SALARY` <double>.
Backtrace:
1. tidyr::replace_na(df, list(AGE= 0, SALARY= "not found"))
2. tidyr:::replace_na.data.frame(df, list(AGE= 0, SALARY= "not found"))
3. vctrs::vec_assign(...)
4. vctrs `<fn>`()
5. vctrs::vec_default_cast(...)
6. vctrs::stop_incompatible_cast(...)
7. vctrs::stop_incompatible_type(...)
8. vctrs:::stop_incompatible(...)
9. vctrs:::stop_vctrs(...)

编辑:这是我的数据集的来源:https://drive.google.com/file/d/1cKxzNrnIMq4RxdMcBz3nlr7YtYaPhn5_/view?usp=sharing

最佳答案

我在更新tidyr到1.2.0版本后遇到了同样的问题

来自 tidyr 的变更日志:

replace_na() no longer allows the type of data to change when the replacement is applied. replace will now always be cast to the type of data before the replacement is made. For example, this means that using a replacement value of 1.5 on an integer column is no longer allowed. Similarly, replacing missing values in a list-column must now be done with list("foo") rather than just "foo".

您正在尝试转换“年龄”和“薪水”两列。

单独转换 'Age' 应该可行,因为它可能是 double 类型,并且您正在将 NA 转换为 0,同时也是 double 类型。

mutate(Age = replace_na(Age, 0) #This should work

但是当您尝试用字符串“not found”在“Salary”中replace_na 时,您必须将该列转换为字符replace_na 过去会自动执行此操作,但现在不会了。您可以通过添加对 as.character

的调用来解决此问题

mutate(Salary = replace_na(Salary, "not found") #used to work

新方法:

mutate(Salary = replace_na(as.character(Salary), "not found") #新方法

关于用 R 中的数字和字符值替换数字列的 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71227130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com