简体   繁体   English

使用 tidyverse 从 R 中的 enite dataframe 中删除字符

[英]Remove character from enite dataframe in R with tidyverse

I have a data frame that has many columns and many rows我有一个有很多列和很多行的数据框

col_1 | col_2 | ... | col_n
---------------------------    
val_1 | val_2 | ... | val_n
val_1 | val_2 | ... | val_n
  .   |   .   |  .  |   . 
  .   |   .   |  .  |   . 
  .   |   .   |  .  |   . 
val_1 | val_2 | ... | val_n

My wish is to remove all commas , from all values with tidyverse.我的愿望是使用 tidyverse 从所有值,删除所有逗号。

How can I achieve this?我怎样才能做到这一点?

Use gsub to replace commas and across to apply it for multiple columns.使用gsub替换逗号并使用 cross 将其across多列。

library(dplyr)
df %>% mutate(across(.fns = ~gsub(',', '', ., fixed = TRUE)))

Or in base R -或在基地 R -

df[] <- lapply(df, function(x) gsub(',', '', x, fixed = TRUE))

We could use str_remove_all and this should comply with tidyverse我们可以使用str_remove_all这应该符合tidyverse

library(dplyr)
library(stringr)
df <- df %>%
          mutate(across(everything(), str_remove_all, ","))

A base R option using gsub使用gsub的基本 R 选项

list2DF(lapply(df, function(v) gsub(",", "", v)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM