Home > Net >  how to replace all 0 (0%) to 0 in a data frame
how to replace all 0 (0%) to 0 in a data frame

Time:11-05

I have an table/df that looks like this:

strong text

How can I replace 0 (0.00%) to 0? I tried str_replace_all and it dosen't work. Any suggestion?

df<-structure(list(SUBJECT = c("PE", "PE", "PE", "PE", "PE", 
"PE"), Class = c("3rd Grade", "3rd Grade", 
"3rd Grade", "3rd Grade", "3rd Grade", 
"3rd Grade"), Number_Student = c(7L, 7L, 7L, 7L, 
7L, 7L), WGRADE = structure(1:6, .Label = c("Grade 0", "Grade 1", 
"Grade 2", "Grade 3", "Grade 4", "Grade 5"), class = "factor"), 
    `Grade 0` = c("1 (14.29%)", "1 (14.29%)", "0 (0.00%)", "0 (0.00%)", 
    "0 (0.00%)", "0 (0.00%)"), `Grade 1` = c("0 (0.00%)", "3 (42.86%)", 
    "1 (14.29%)", "0 (0.00%)", "0 (0.00%)", "0 (0.00%)"), `Grade 2` = c("0 (0.00%)", 
    "0 (0.00%)", "0 (0.00%)", "1 (14.29%)", "0 (0.00%)", "0 (0.00%)"
    ), `Grade 3` = c("0 (0.00%)", "0 (0.00%)", "0 (0.00%)", "0 (0.00%)", 
    "0 (0.00%)", "0 (0.00%)"), `Grade 4` = c("0 (0.00%)", "0 (0.00%)", 
    "0 (0.00%)", "0 (0.00%)", "0 (0.00%)", "0 (0.00%)"), `Grade 5` = c("0 (0.00%)", 
    "0 (0.00%)", "0 (0.00%)", "0 (0.00%)", "0 (0.00%)", "0 (0.00%)"
    )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

CodePudding user response:

dplyr solution:

df %>%
    mutate(
    across(where(is.character), str_replace_all, '0 (0.00%)', '0')
)

CodePudding user response:

R-base solution:

df[ df == "0 (0.00%)"] <- "0"
  •  Tags:  
  • r
  • Related