5

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

4
  • 1
    Just do data[] <- lapply(data, gsub, pattern = "sfsdf", replacement = "Hi") Commented Jul 10, 2019 at 3:58
  • You mean, data[,c("col1", "col3", "col5") <- lapply(data, gsub, pattern = "sfsdf", replacement = "Hi") Like this? Commented Jul 10, 2019 at 4:00
  • 2
    I meant data[,c("col1", "col3", "col5")] <- lapply(data[,c("col1", "col3", "col5")], gsub, ... Commented Jul 10, 2019 at 4: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 and reading up on How to ask a good question? would be a good start. you'll be awarded a badge! ... Meanwhile, I think this is a dupe! Commented Jul 10, 2019 at 4:03

1 Answer 1

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"))
Sign up to request clarification or add additional context in comments.

2 Comments

does this lapply solution solve the original post? I tried it and you start with a dataframe and end up with a list.
@MasonK It should solve the question posted. I don't know about the structure of your input data nor the function applied.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.