Rachel Ward
Rachel Ward

Reputation: 35

How to add parentheses to column values in a data frame in R?

I'm working with sensitive data, so I created a fake data frame that can serve as an example. This is what we're working with.

n    percent
4     36%
5     51%
6     61%
7     71%
8     84%
9     96%
10    100%

Pretty simple. I want to change the percent column so that the values have parentheses around them. So essentially, I want the data frame to look like this:

n  Percent
4   (36%)
5   (51%)
6   (61%)

I realize that this will make it a string, but that's not a problem for my ultimate purposes. I wrote a function that returns the column as a vector with parentheses.

addparentheses <- function(x){paste("(", x, ")")}

addparentheses (sample_data$percent)

[1] "( 36% )" "( 51% )" "( 61% )" "( 71% )" "( 84% )" "( 96% )" "( 100% )"

How can I write something like this so that it actually changes the data frame and doesn't just return a vector?

Any ideas and insights are much appreciated. Thanks!!

Upvotes: 3

Views: 5291

Answers (1)

ciakovx
ciakovx

Reputation: 334

library(dplyr)
x <- tibble(
  n = 4:10,
  pct = paste0(4:10, "%")
)

x <- x %>%
  mutate(pct = paste0("(", pct, ")"))

Or in base R

x$pct <- paste0("(", x$pct, ")")

Upvotes: 5

Related Questions