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?" " \") "
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?")