How can I use gsub in multiple specific column in r [duplicate]

我与影子孤独终老i 提交于 2021-02-11 12:47:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!