gpt4 book ai didi

r - 无法为 R 中的列表替换 NA 的拼写错误

转载 作者:行者123 更新时间:2023-12-05 09:06:55 24 4
gpt4 key购买 nike

我想将此拼写错误 “-” 替换为 NA 以获取 R 中的 df 列表,

我正在使用以下代码,但它会抛出一个错误;

还有其他方法可以完成这个任务吗?

代码

df_list <- lapply(df_list, function(x){
is.na(x) <- x == "-"
x
})

控制台输出

Error in charToDate(x) : 
character string is not in a standard unambiguous format

数据



df1 <- data.frame(a = c(1, 2, "-"), dates = seq(as.Date("2021/01/01"),
as.Date("2021/01/03"),
by = "month"),
strings = c("hello how are you", "hey man", "-"))

df2 <- data.frame(b = c(3,4, "-"),
dates = seq(as.Date("2021/01/01"),
as.Date("2021/01/03"),
by = "month"),
strings = c("hello how are you", "yoooo", "-")
)

df3 <- data.frame(c = c(5, "-", 7),
dates = seq(as.Date("2021/01/01"),
as.Date("2021/01/03"),
by = "month"),
strings = c("hello how are you", "hello world", "-"))


df_list <- list(df1,df2,df3)

最佳答案

您可以使用as.matrix 将列表中的所有元素转换为字符,即

> lapply(df_list, function(x) replace(x, as.matrix(x) == "-", NA))
[[1]]
a dates strings
1 1 2021-01-01 hello how are you
2 2 2021-01-01 hey man
3 <NA> 2021-01-01 <NA>

[[2]]
b dates strings
1 3 2021-01-01 hello how are you
2 4 2021-01-01 yoooo
3 <NA> 2021-01-01 <NA>

[[3]]
c dates strings
1 5 2021-01-01 hello how are you
2 <NA> 2021-01-01 hello world
3 7 2021-01-01 <NA>

关于r - 无法为 R 中的列表替换 NA 的拼写错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65571188/

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