问题
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
回答1:
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"))
来源:https://stackoverflow.com/questions/56963214/how-can-i-use-gsub-in-multiple-specific-column-in-r