在 R 中删除多个变量中的字符串

问题描述

这是我的数据的 MWE,我想从中删除包含“Med”的所有列中的字符串“NaN”

df= data.frame(id= rep(1:5,each=1),Med1 = c("GN","GN","Ca","DM"),Med2 = c("DM","NaN","Mob","NaN"),Med3 = c("NaN","DM","NaN"))

我尝试了以下方法

dfx = df%>%
  mutate(across(contains("Med",ignore.case = TRUE),str_remove(.,"NaN")))
Error: Problem with `mutate()` input `..1`.
x Problem with `across()` input `.fns`.
i Input `.fns` must be NULL,a function,a formula,or a list of functions/formulas.
i Input `..1` is `(function (.cols = everything(),.fns = NULL,...,.names = NULL) ...`.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
Problem with `mutate()` input `..1`.
i argument is not an atomic vector; coercing
i Input `..1` is `(function (.cols = everything(),.names = NULL) ...`. 
dfx = df%>%
  mutate(across(contains("Med",str_remove("NaN")))
Error: Problem with `mutate()` input `..1`.
x argument "pattern" is missing,with no default
i Input `..1` is `(function (.cols = everything(),.names = NULL) ...`.

我也有从单列中删除字符串的问题,所以我想我可能误解了 str_remove

dfy=df%>%
 str_remove(string = Med1,pattern = "NaN")
Error in str_remove(.,string = Med1,pattern = "NaN") : 
  unused argument (.)

解决方法

预先:在代码中添加波浪号:

dfx = df%>%                                        #,--- add this tilde
  mutate(across(contains("Med",ignore.case = TRUE),~ str_remove(.,"NaN")))

说明:across 将函数作为第二个参数。这可以通过以下几种方式表达:

  1. 原始函数,例如across(everything(),mean)。之后您可以添加任意命名/未命名参数,但它们与数据本身是分开的。

    mtcars %>%
      mutate(across(everything(),mean))
    mtcars %>%
      mutate(across(everything(),mean,na.rm = TRUE))
    

    (这不假设 base-R 函数:您可以在其他地方创建自己的函数并在此处传递。)

  2. 匿名函数,允许更灵活的调用。也许:

    mtcars %>%
      mutate(across(everything(),function(z) mean(x)))
    mtcars %>%
      mutate(across(everything(),function(z) mean(x,na.rm = TRUE)))
    
  3. rlang 样式的波浪号函数。在这些中,. 被数据向量替换(对于每列是 mutated):

    mtcars %>%
      mutate(across(everything(),~ mean(.)))
    mtcars %>%
      mutate(across(everything(),~ mean(.,na.rm = TRUE)))
    

当然,您不需要 stringr 来执行这个任务。

df
#   id Med1 Med2 Med3
# 1  1   GN   DM  NaN
# 2  2   GN  NaN  NaN
# 3  3   Ca  Mob   DM
# 4  4   Ca  NaN  NaN
# 5  5   DM  NaN  NaN
df[df == "NaN"] <- ""
df
#   id Med1 Med2 Med3
# 1  1   GN   DM     
# 2  2   GN          
# 3  3   Ca  Mob   DM
# 4  4   Ca          
# 5  5   DM          

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...