Search code examples
rknitrgsubkable

Substituting symble without removing the column


enter image description here

The added image is created from the following code:

  B <- addmargins(table(data$range, data$symbols))
   B[] <- sprintf('%s (%s)', as.matrix(B), paste0(round(prop.table(as.matrix(B), 1), 2) * 200, '%'))
   knitr::kable(B)%>%
   kable_styling(bootstrap_options= c("striped", "hover"), font_size=16, position="center")
   ```

The last column is called SUM, which you can see. I want to remove the % sign from the last column. To achieve this, I tried using gsub like so

res <- gsub("%","", B[ , ncol(B[])])
knitr::kable(res)%>%
kable_styling(bootstrap_options= c("striped", "hover"), font_size=16, position="center")
```

It does remove the % signs, but it also removes all the other columns, and only shows the last column. How can I make it keep the other columns?


Solution

  • First, you can avoid the need to remove "%" by just adding percentages to columns that do not include the Sum column (referring to B[,-ncol(B)] instead of B or B[] in the sprintf statement will add percentages to all columns except the last one).

    In addressing the posted question, using made up data based on the example image above:

    B <- data.frame(
      O = c("14 (54%)", "20 (64%)"),
      A = c("9 (34%)", "5 (16%)"),
      AB = c("0 (0%)", "1 (4%)"),
      B = c("3 (12%)", "5 (16%)"),
      Sum = c("26 (100%)", "31 (100%)")
    )
    

    You can use the following to just remove "%" (original question):

    B[,ncol(B)] <- sub("%", "", B[,ncol(B)])
    B
    
             O       A     AB       B      Sum
    1 14 (54%) 9 (34%) 0 (0%) 3 (12%) 26 (100)
    2 20 (64%) 5 (16%) 1 (4%) 5 (16%) 31 (100)
    

    To remove the open parenthesis "(" and everything after it (follow up comment) you can do:

    B[,ncol(B)] <- sub(" \\(.*", "", B[,ncol(B)])
    B
    
             O       A     AB       B Sum
    1 14 (54%) 9 (34%) 0 (0%) 3 (12%)  26
    2 20 (64%) 5 (16%) 1 (4%) 5 (16%)  31
    

    To remove both the parentheses and all text contained between them, you can do:

    B[,ncol(B)] <- sub(" \\(.*)", "", B[,ncol(B)])
    B
    

    Note: If you have multiple parentheses, you can use gsub and a different pattern.