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

我想将此拼写错误 “-” 替换为 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/

相关文章:

awk - 将 awk 应用于除第一行以外的所有内容

powershell - 无法注册 PS 图库

javascript - 如果 "any"不能在 Nest.js 中使用,模式中的字段类型应该是什么

reactjs - firebase safari 错误消息 : This browser does

java - 更正应包含单个兼容版本的应用程序的类路径

python - numpy 中的 3d 矩阵乘法

c - STM32创建RAM段

c# - 有没有办法在 Switch 表达式中跳过或继续,或者每个分支都需要返回一些东西?

java - 在 Clojure 中使用 JSoup 解析字符串

c++ - 找不到 Glog(缺少 : GLOG_INCLUDE_DIR GLOG_LIBRARY)