Rilcon42
Rilcon42

Reputation: 9765

append row to row using dplyr

How can I take a row that is exactly the same (except for the number on the end) and append it to another row? I tried using

df<-data.frame(
  Participant=c("bob1","bill1","bob2","bill2"),
  No_Photos=c(1,4,5,6)
)

library(tidyr)
library(dplyr)
df%>% Participant = gsub("[0-9]", "", Participant) %>% group_by(Participant) %>% rbind(Participant[1],Participant[2])

Goal:

Participant No_Photos Participant No_Photos
Bill1        4        Bill2       6
Bob1         1        Bob2        5

Upvotes: 0

Views: 446

Answers (2)

akrun
akrun

Reputation: 886938

Here is an option using data.table. We extract the non-numeric characters from 'Participant' to create 'ind', then using that we get the sequence ('N') and then convert to wide format with dcast.

library(data.table)
setDT(df)[, ind := sub('\\D+', '', Participant)][, N:= 1:.N, ind]
dcast(df, N~ind, value.var=c('Participant', 'No_Photos'))
#   N Participant_1 Participant_2 No_Photos_1 No_Photos_2
#1: 1          bob1          bob2           1           5
#2: 2         bill1         bill2           4           6

Upvotes: 1

bramtayl
bramtayl

Reputation: 4024

I think you might want something like this:

library(tidyr)
library(dplyr)
library(rex)

df %>% 
  extract(Participant,
          c("name", "number"),
          rex(capture(letters), capture(numbers)),
          remove = FALSE) %>%
  gather(variable, value, 
         No_Photos, Participant) %>%
  unite(new_variable,
        variable, number) %>%
  spread(new_variable, value)

Upvotes: 0

Related Questions