mardi 31 juillet 2018

R for loop with if else on multiple data frames

Greetings and thanks in advance for all help I have many data frame that resemble the ones below

df1

   name info
1  john    A
2   jim    B
3   tom    B
4 bill     B

dframe

  name other
1  sam   pro
2  dad   mo1
3  mom  Bxxx

frame3

   name otherinfo
1   jus         A
2    do         7
3 r pro         B
4   sir         B
5  real        na
6  pete       yes

OLFrame

   name information
1  ally          x1
2   mom          B9
3 r pro         s3B
4   tom         Bd0
5 kelly          ot
6  jojo         who
7    na          11

I would like to :

  1. take each name from the "name" collumn of dataframe "OLFrame" and look into the "name"collum of "df1"to see if the name exists
  2. create collum vector with named "df1" consisting of "1" if name from "OLFrame" exist in "df1" if not "0"
  3. reapeat the steps 1 and 2 but using "dframe" and "frame3"
  4. create a new data frame called "newOLFrame" consisting of "OLFrame" and and new columns named "df1", "dframe" and "frame3"

The desired result should look like

newOLFrame

   name information df1 dframe frame3
1  ally          x1   0      0      0
2   mom          B9   0      1      0
3 r pro         s3B   0      0      1
4   tom         Bd0   1      0      0
5 kelly          ot   0      0      0
6  jojo         who   0      0      0
7    na          11   0      0      0

I can do one at a time (below) but I have over a hundred files to look through

newOLFrame<-OLFrame
newOLFrame[,"pro1"]<-ifelse(newOLFrame$name %in% df12$name, 1, 0)

Please help. Thanks again

Aucun commentaire:

Enregistrer un commentaire