0

I am new to loops and I am trying to find an easier way to do the following:


MHdata1<- anti_join(MHdata1, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata,MHdata1)
MHdata2<- anti_join(MHdata2, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata, MHdata2)
MHdata3$IDNumber<- as.numeric(MHdata3$IDNumber)
MHdata3<- anti_join(MHdata3, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata, MHdata3)
MHdata4$IDNumber<- as.numeric(MHdata4$IDNumber)
MHdata4<- anti_join(MHdata4, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata, MHdata4)
MHdata5<- anti_join(MHdata5, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata, MHdata5)
MHdata6<- anti_join(MHdata6, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata, MHdata6)
MHdata7<- anti_join(MHdata7, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata, MHdata7)
MHdata8$IDNumber<- as.numeric(MHdata8$IDNumber)
MHdata8<- anti_join(MHdata8, MHdata, by = "IDNumber")
MHdata<- rbind(MHdata, MHdata8)

the MHdata tables are the same tables of different months. However in some of those tables, the IDNumber is char instead of num. So I thought of doing something like:

series<- 1:8
for (i in series) {
  MHdata[[i]]<- as.numeric(MHdata[[i]][ ,3]) ##convert the 3rd column (IDNumber) in each table
  MHdata[[i]]<- anti_join(MHdata[[i]],MHdata,by = "IDNumber") #anti join to remove pre-existing IDnumbers
  MHdata<- rbind(MHdata,MHdata[[i]]) #bind the two
}

Rationale is

  1. convert 3rd column of each MHdata table into numeric
  2. anti join the MHdata[i] with the main MHdata table. This seperates those IDs in MHdata from those that are new.
  3. rbind the two so the main MHdata includes those IDs that weren't there before

I am sure there must be an easier way to do it. Ideally I want to reduce the 8 repetitions into a loop if possible!

Edit: I managed to make the below work

Convertcols = function(x) { ##this function turns the 3rd column into numeric
  x[,3]<- as.numeric(x[,3])
  return(x)
}

MHlist<- list(MHdata0,MHdata1,MHdata2,MHdata3,MHdata4,MHdata5,MHdata6,MHdata7,MHdata8)
MHlist1<- lapply(MHlist, Convertcols) #Returns list of renamed data frames.

outbis <- list()
for(i in seq_along(MHlist1)) {
  outbis[[i]] <- anti_join(MHlist1[[i]], MHdata, by = "IDNumber")
  MHdata<- rbind(MHdata, outbis[[i]])
  names(outbis)[i] <- paste0("MHdata", names(MHlist1)[i])
}
Nick9714
  • 1
  • 1
  • 3
    [Put your data frames in a `list`](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames). – Gregor Thomas Jun 13 '23 at 14:16

0 Answers0