mercredi 3 novembre 2021

A problem with ifelse according to two variables from different dataframes in R

I have two data frames. The first one (A) contain information about GOALS, and the second one (B) contains the specific information about the IDs which had that GOAL:

> A
          GOAL
1 A116642173
2 A116642174
3 A116642175
4 A116642176
5 A116642178
6 A116642181 

> B
    ID         GOAL
1 1873 A116433509
2  478 A116642178
3 2165 A116192937
4  165 A116192937
5  313 A116433701
6  475 A116367456

I would like to create new columns in one of this according the other data frame. So, first I create aditional columns:

> idkids=c(313,475,165,478,1873,2165)
> ids<-c(idkids)
> A[ ,paste0(ids)]<-0
> A
          GOAL 313 475 165 478 1873 2165
1 A116642173   0   0   0   0    0    0
2 A116642174   0   0   0   0    0    0
3 A116642175   0   0   0   0    0    0
4 A116642176   0   0   0   0    0    0
5 A116642178   0   0   0   0    0    0
6 A116642181   0   0   0   0    0    0 

I tried to use ifelse to find the GOAL for a specifid ID, but I didn't. I have tried to do this by two ways:


for (i in 1:kids){
  A[ ,i+1]<-ifelse(A[ ,i+1]%in%B$ID,"",
                   ifelse(A$GOAL%in%B$GOAL, 1, 0))
}


for (i in 1:kids){
  A[ ,i+1]<-ifelse(A[,i+1]%in%B$ID & A$GOAL%in%B$GOAL,1,0)
}

But my code didn't recognize the specific ID and it didn't give me 1 (TRUE) or 0 (FALSE). It give me 0 for all the columns... Can any one help me, please?

Aucun commentaire:

Enregistrer un commentaire