0

I can't figure out how to add a new row to a dataframe according conditions found in another one.
For example, I have two dataframes, one with the data (df1) and smaller one with the conditions associated to the observations (df2). Columns names (id1 and id2) to identify the observations are different in the two dataframes but the variables ("a", "b"...) are identical.
I would like R to check in df2 if the observation "a" (of the column id2) has a result = "TRUE" or "FALSE" and, report the result accordingly in df1 in a new colum df1$idTF.

df1 <- data.frame(id1 = c("a","b","a","c","b","a","c","a","a","b"), 
mes1 = c(2,3,4,2,3,5,2,3,4,2), mes2 = c(56,33,64,72,83,59,26,37,48,29))

> df1
  id1 mes1 mes2
1   a    2   56
2   b    3   33
3   a    4   64
4   c    2   72
5   b    3   83
6   a    5   59
7   c    2   26
8   a    3   37
9   a    4   48
10  b    2   29

df2 <- data.frame(id2 = c("a","b","c"), result = c("TRUE","FALSE","TRUE"))

> df2
    id2 result
1    a   TRUE
2    b  FALSE
3    c   TRUE

I would like add a new colum to df1 (df1$idTF) according the TRUE or FALSE condition of the id found in the df2 in order to get something like that:

> df1
   id1 mes1 mes2  idTF
1   a    2   56  TRUE
2   b    3   33 FALSE
3   a    4   64  TRUE
4   c    2   72  TRUE
5   b    3   83 FALSE
6   a    5   59  TRUE
7   c    2   26  TRUE
8   a    3   37  TRUE
9   a    4   48  TRUE
10  b    2   29 FALSE

So far I havent find a way to do this (nested loops ?). In fact my database has 1700 rows and there are 58 differents conditions in the other dataframe.

CharlesLDN
  • 169
  • 1
  • 9
  • 1
    There are hundreds of ways of doing it. For instance `merge(df1,df2,all.x=TRUE)` or `df1$idTF<-df2$result[match(df1$id,df2$id)]` or several other ways using `data.table` or `dplyr`. – nicola Jan 11 '18 at 08:22
  • Nicola, thank you for your quick reply and expertise. I have made my question a bit more clearer as what I want to do is a bit more complicated. I already tried merge and dplyr without success. – CharlesLDN Jan 11 '18 at 13:28
  • After hours of searching, I finally manage to get the answer from this post: (https://stackoverflow.com/questions/42613167/replace-values-in-dataframe-column-based-on-match-in-second-data-frame-columns). `df1 $ idTF <- df2 $ result [match( df1 $ id1, df2 $ id2)]` – CharlesLDN Jan 17 '18 at 20:39

0 Answers0