4

Could you help me please for answer the little Q?

I have data.frame like under. than,

I want to use gsub function specific column in data.frame easily

Because the change character is SAME! but I want change lots of specific column.

In example code, It have just 4 column but my data have over 10 column, and I want change 6~7 specific column (not continuous).

And changing same text...

Please help Thanks

I'm doing like these

data$col1<-gsub("sfsdf", "Hi", data$col1)
data$col3<-gsub("sfsdf", "Hi", data$col3)
data$col4<-gsub("sfsdf", "Hi", data$col4)

and so on...

It`s too many column...

col1 <- 1:10   
col2 <- 21:30   
col3 <- c("503.90", "303.90 obs", "803.90sfsdf sf", "203.90 obs", "303.90", "103.90 obs", "303.90", "403.90 obs", "803.90sfsdf sf", "303.90 obs")   
col4 <- c("303.90", "303.90 obs", "303.90", "203.90 obs", "303.90", "107.40fghfg", "303.90", "303.90 obs", "303.90", "303.90 obs")

data <- data.frame(col1, col2, col3, col4)

data$col3 <- as.factor(data$col3)
data$col4 <- as.factor(data$col4)

Using gsub on columns in R

neilfws
  • 32,751
  • 5
  • 50
  • 63
user11762308
  • 65
  • 2
  • 7
  • 1
    Just do `data[] <- lapply(data, gsub, pattern = "sfsdf", replacement = "Hi")` – akrun Jul 10 '19 at 03:58
  • You mean, data[,c("col1", "col3", "col5") <- lapply(data, gsub, pattern = "sfsdf", replacement = "Hi") Like this? – user11762308 Jul 10 '19 at 04:00
  • 2
    I meant `data[,c("col1", "col3", "col5")] <- lapply(data[,c("col1", "col3", "col5")], gsub, ...` – akrun Jul 10 '19 at 04:01
  • 2
    This is your second question which can be easily answered by an online search and reading about `lapply`. While we are here to help, I think you should do a little bit of research on what type of questions are acceptable, what should I do before asking a question, etc. Perhaps taking the [tour](https://stackoverflow.com/tour) and reading up on [How to ask a good question?](https://stackoverflow.com/help/how-to-ask) would be a good start. you'll be awarded a badge! ... Meanwhile, I think this is a dupe! – M-- Jul 10 '19 at 04:03

1 Answers1

6

We can use lapply to loop over the columns and apply the gsub

nm1 <- c("col1", "col3", "col5") 
data[nm1] <- lapply(data[nm1], gsub, pattern = "sfsdf", replacement = "Hi")

Or another option is mutate_at

library(dplyr)
data %>%
    mutate_at(vars(nm1), ~ str_replace(., "sfsdf", "Hi"))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • does this lapply solution solve the original post? I tried it and you start with a dataframe and end up with a list. – MasonK Nov 11 '20 at 21:58
  • @MasonK It should solve the question posted. I don't know about the structure of your input data nor the function applied. – akrun Nov 11 '20 at 22:00