Sophia
Sophia

Reputation: 99

Extracting certain strings to concatenate by ID in R

I am trying to extract certain treatment methods and then concatenate them by ID in R using tidyverse functions. Could someone please help out with the code please? I have been trying stringr but have not been successful. I have this picture of what I have and what I need to get to. The data on the left is an example of what I have and the data on the right is what I need it to look like. The list of strings I am pulling out here is A, B, and D. The data on the left is an example of what I have and the data on the right is what I need it to look like. The list of strings I am pulling out here is A, B, and D.

Upvotes: 1

Views: 68

Answers (1)

akrun
akrun

Reputation: 887183

An option is to filter the 'Treatment' to subset the rows, then do a group by 'ID' and paste the sorted unique values of 'Treatment'

library(dplyr)
df1 %>%
  filter(Treatment %in% c("A", "B", "D")) %>%
  group_by(ID) %>%
  summarise(Treatment = toString(sort(unique(Treatment))))

Or with base R

aggregate(Treatment ~ ID, unique(subset(df1, Treatment %in% c('A', 'B', 'D')), toString)

Upvotes: 2

Related Questions