Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

r - String substitutions across multiple columns in tidyverse

My data frame

>df <- data.frame(Names = c("A", "B", "C"), Total = c("125", "2 500", "1 350"), 
>           Boys = c("50", "1 500", "350"),
>           Girls = c("75", "1 000", "1 000")) 
  Names Total  Boys Girls
1     A   125    50    75
2     B 2 500 1 500 1 000
3     C 1 350   350 1 000

All values are strings. I want to substitute spaces " " to non spaces "" in Total, Boys and Girls. I know about

df %>%
  mutate(Total = gsub(" ", "", Total),
         Boys = gsub(" ", "", Boys),
         Girls = gsub(" ", "", Girls))

But is there a (tidyverse style) way to do this more generally? Something like

df %>% # (This don't work)
  mutate(across(c(Total, Boys, Girls), gsub(" ", "", .x)))

I.e. I'm looking for a solution that scales well.

Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use :

library(dplyr)

df %>% mutate(across(c(Total, Boys, Girls), ~as.numeric(gsub(" ", "", .))))

#  Names Total Boys Girls
#1     A   125   50    75
#2     B  2500 1500  1000
#3     C  1350  350  1000

Or in base R with lapply :

df[-1] <- lapply(df[-1], function(x) as.numeric(gsub(" ", "", x)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...