Home > OS >  Manipulating character vectors: removing and adding quotes, adding strings
Manipulating character vectors: removing and adding quotes, adding strings

Time:03-30

I have vector_1, which I want to manipulate with code so that vector_2 and vector_3 are generated automatically.

# What I have
> vector_1 <- c("Group_A", "Group_B", "Group_C", "Group_D")
> vector_1
[1] "Group_A" "Group_B" "Group_C" "Group_D"

I want to achieve the following:

# What I want to achieve by manipulating vector_1: 
vector_2 = c("Group_A, Group_B, Group_C, Group_D")
vector_3 = c(" ", "Group_A" = 3, "Group_B" = 3, "Group_C" = 3, "Group_D" = 3))

I assume noquote() is a starting point, but then I get stuck.

> vector_x <- noquote(vector_1)
> vector_x
[1] Group_A Group_B Group_C Group_D
# Here I'm stuck...

Base R would do, but I prefer to work in the tidyverse, with or without pipes.

--- Edit ---

Following up Sotos' question in the comments:

I want to use vector_3 as a header in kableExtra. Instead of writing...

kbl(
[hidden code] %>%
add_header_above(c(" ", "Group_A"=3, "Group_B"=3, "Group_C"=3, "Group_D"=3)) %>%
[more_code]
)

I haven't been able to make a reproducible example that works outside of PDF. Here's a link to add_header_above():

https://www.rdocumentation.org/packages/kableExtra/versions/1.3.4/topics/add_header_above

CodePudding user response:

You can use toString for vector_2, and setNames for vector_3:

toString(vector_1)
# [1] "Group_A, Group_B, Group_C, Group_D"

c(" ", setNames(rep(3, 4), vector_1))
#        Group_A Group_B Group_C Group_D 
#    " "     "3"     "3"     "3"     "3" 

CodePudding user response:

vector_2:

paste(vector_1, collapse = ", ")
# [1] "Group_A, Group_B, Group_C, Group_D"

And vector_3:

setNames(c(" ", rep(3, length(vector_1))), c("", vector_1))
#     Group_A Group_B Group_C Group_D 
# " "     "3"     "3"     "3"     "3" 
  • Related