我想将此拼写错误 “-”
替换为 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>
https://stackoverflow.com/questions/65571188/