0

I need to prepare queries that are made of characters strings (DOI, Digital Object Identifier) stored in a data frame. All strings associated with the same case have to be joined to produce one query.

The df looks like this:

Case DOI
1 1212313/dfsjk23
1 322332/jdkdsa12
2 21323/xsw.w3
2 311331313/q1231
2 1212121/1231312

The output should be a data frame looking like this:

Case Query
1 DO=(1212313/dfsjk23 OR 322332/jdkdsa12)
2 DO=(21323/xsw.w3 OR 311331313/q1231 OR 1212121/1231312)

The prefix ("DO="), suffix (")") and "OR" are not critical, I can add them later, but how to aggregate character strings based on a case number?

2 Answers 2

2

In base R you could do:

aggregate(DOI~Case, df1, function(x) sprintf('DO=(%s)', paste0(x, collapse = ' OR ')))
  Case                                                     DOI
1    1                 DO=(1212313/dfsjk23 OR 322332/jdkdsa12)
2    2 DO=(21323/xsw.w3 OR 311331313/q1231 OR 1212121/1231312)

if Using R 4.1.0

aggregate(DOI~Case, df1, \(x)sprintf('DO=(%s)', paste0(x, collapse = ' OR ')))
Sign up to request clarification or add additional context in comments.

Comments

0

We can use glue with str_c to collapse the 'DOI' column after grouping by 'Case'

library(stringr)
library(dplyr)
df1 %>%
   group_by(Case) %>%
   summarise(Query = glue::glue("DO=({str_c(DOI, collapse= ' OR ')})"))

-output

## A tibble: 2 x 2
#   Case Query                                                  
#  <int> <glue>                                                 
#1     1 DO=(1212313/dfsjk23 OR 322332/jdkdsa12)                
#2     2 DO=(21323/xsw.w3 OR 311331313/q1231 OR 1212121/1231312)

data

df1 <- structure(list(Case = c(1L, 1L, 2L, 2L, 2L), DOI = c("1212313/dfsjk23", 
"322332/jdkdsa12", "21323/xsw.w3", "311331313/q1231", "1212121/1231312"
)), class = "data.frame", row.names = c(NA, -5L))

1 Comment

New to this site, thank you for pointing this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.