0

Could someone please help me while I'm trying to build this final line:

[1] ("mercury" AND "earth" AND "Jupiter" AND "Uranus" AND "Pluto?") 

By using below code

df <- structure(list(AND = c("mercury", "earth", "Jupiter", "Uranus", 
"Pluto?"), OR = c("venus", "Mars", "Saturn", "Neptune", "")), class = "data.frame", row.names = c(NA, 
-5L))

# fist
first <- str_c(c(' (" ' ,df$AND[1], ' "  ' ), sep = "")

# in between
between <- str_c(df$AND[2:(nrow(df) - 1)], sep = '  " AND "  ')

# last
last <- str_c(c(' " ',df$AND[nrow(df)], ' ")  ' ), sep = "")

# full

str_c(c(first,between,last), sep = "")

But this how my result looks like:


[1] " (\" "   "mercury" " \"  "   "earth"   "Jupiter" "Uranus"  " \" "    "Pluto?"  " \")  " 
MelaniaCB
  • 427
  • 5
  • 16

2 Answers2

2

You can use :

library(stringr)
str_c('(', str_c(excel$AND, collapse  = ' AND '), ')')
#Similar using paste0
#paste0('(', paste0(excel$AND, collapse  = ' AND '), ')')
#[1] "(mercury AND earth AND Jupiter AND Uranus AND Pluto?)"

OR a base R version would be :

sprintf('(%s)', paste0(excel$AND, collapse  = ' AND '))
#[1] "(mercury AND earth AND Jupiter AND Uranus AND Pluto?)"

If we need quotes around each word we can twist sprintf output to :

tmp <- sprintf('("%s")', paste0(excel$AND, collapse  = '" AND "'))
cat(tmp)
#("mercury" AND "earth" AND "Jupiter" AND "Uranus" AND "Pluto?")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Hi, thanks! But what I actually need is to buil this lines = `("mercury" AND "earth" AND "Jupiter" AND "Uranus" AND "Pluto?")` Sorry for not making myself clear! – MelaniaCB Sep 15 '20 at 00:57
  • 2
    @MelaniaCB So `sprintf('("%s")', paste0(excel$AND, collapse = '" AND "'))` . Note that R escapes `"` so you see those `"\"`. Use `cat` to see actual string `cat(sprintf('("%s")', paste0(excel$AND, collapse = '" AND "')))` – Ronak Shah Sep 15 '20 at 01:02
  • Oh wow! Amazing - Exactly what I needed! Additional thanks on the explanation – MelaniaCB Sep 15 '20 at 01:21
0

We can use glue

 with(df, as.character(glue::glue("{paste(AND, collapse=' AND ')}")))
#[1] "mercury AND earth AND Jupiter AND Uranus AND Pluto?"
akrun
  • 874,273
  • 37
  • 540
  • 662