loops and changes to columns

I am trying to change remove a letter in the string of few columns in a data frame. I am having trouble working on the gsub command. I can use the gsub() command to remove a letter in a string but having trouble putting that in the loop and making it work on few of the columns. Please help. Here is my code.

Thanks.

i1 <- 1
for(i1 in 1:4){
HW_Scores_br.df_test2$HW[i1] <- gsub("m", " ", paste(HW_Scores_br.df_test2$HW[i1]))
view(HW_Scores_br.df_test2$HW[i1])
}

This kind of column manipulation is not typically done with a for loop. There are many functions available to change the content of columns or add new columns. Below is an example of replacing every m with an empty string in columns whose name starts with HW.


library(dplyr)
DF <- data.frame(Name = LETTERS[1:4],
                 HW1 = c("UmI", "AAA", "mop", "GHR"),
                 Name2 = LETTERS[11:14],
                 HW2 = c("uuu", "jnm", "IOP", "mmJ"))
DF
#>   Name HW1 Name2 HW2
#> 1    A UmI     K uuu
#> 2    B AAA     L jnm
#> 3    C mop     M IOP
#> 4    D GHR     N mmJ
FuncM <- function(x) gsub("m", "", x)
DF2 <- DF %>% mutate_at(vars(matches("HW")), .funs = FuncM)

DF2
#>   Name HW1 Name2 HW2
#> 1    A  UI     K uuu
#> 2    B AAA     L  jn
#> 3    C  op     M IOP
#> 4    D GHR     N   J

Created on 2019-10-09 by the reprex package (v0.3.0.9000)

2 Likes

Thank you. It worked.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.