1

I have a problem with in Shiny which I will show in a simple example:

I have the following data:

Group<-c("A","A","B","C","C","D")
Value<-c(1,2,6,7,3,9)

df<-data.frame(Group, Value)

  Group Value 
     A     1   
     A     2   
     B     6   
     C     7   
     C     3   
     D     9   

Then I add a row to see how many reps a group has:

df$num <- ave(df$Value, df$Group,  FUN = seq_along)

  Group Value num
     A     1   1
     A     2   2
     B     6   1
     C     7   1
     C     3   2
     D     9   1

Now, I would like it, to check if the group contains a 2nd rep, and if not, duplicate the 1st row of the group (containing num=1) and setting num to 2. So I would like to end up with:

  Group Value num
     A     1   1
     A     2   2
     B     6   1
     B     6   2 #this row is added
     C     7   1
     C     3   2
     D     9   1
     D     9   2 #this row is added

I have tried to search for solution, but I mainly ended up with subject like a condition that is based on a certain value, rather than conditions within a group.

Could someone help me? I would appreciate it a lot!

Lotw
  • 423
  • 1
  • 4
  • 15

1 Answers1

0

Can this code do the trick ?

res <- lapply(unique(df$Group), function(x){
  a <- df[df$Group == x, ]
  if(nrow(a) == 1) {
    a <- a[rep(row.names(a), 2), ]
    a$num <- c(1:2)
  }
  a
})
do.call(rbind, res)
Bambs
  • 545
  • 4
  • 14
  • Yes! Thank you! I just came across an extra problem, I tried to change your answer but I can't.... what if this is my dataset: – Lotw Oct 26 '18 at 06:13
  • Sorry, again: @Pauline Thank you! This works perfectly :) I just ran into a new problem, would you know how it works when I have the following data: Group1<-c("A","A","A","A","B","B","B") Group2<-c("A","A","B","B","A","A", "B") Value<-c(1,2,6,7,3,9,6) df<-data.frame(Group1,Group2, Value) df and now I would like to do the same as before but now it would search for duplicates of Group2 within Group1? Thanks again for you answer, it really helps me out! – Lotw Oct 26 '18 at 06:24
  • 1
    There is probably a simplier way to do this but I think this works : res <- lapply(unique(df$Group1), function(x){ int_res <- lapply(unique(df[df$Group1 == x, "Group2"]), function(z) { a <- df[df$Group1 == x & df$Group2 == z, ] if(nrow(a) == 1) { a <- a[rep(row.names(a), 2), ] } a }) do.call(rbind, int_res) }) do.call(rbind, res) – Bambs Oct 26 '18 at 08:50