Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional adding certain data column from two data file

Tags:

r

I have a question on conditional adding certain column from two data files. For instance, I have this data file:

Data 1

ID  purchased
1   5
2   3
3   3
4   3
5   3
6   4
7   4
8   4
9   4
10  4

Data 2

ID  Date3   Date4   Date5
1   2014    2013    2017
2   2014    2015    2012
3   2013    2016    2014
4   2015    2017    2014
5   2016    2012    2017
6   2017    2013    2017
7   2012    2013    2012
8   2014    2013    2014
9   2014    2015    2014
10  2015    2016    2015

So in the two files, the number on the purchase column (data 1) link to a specific date. For example, ID 1 purchased 5 (data 1) should link to ID 1 Date5 (data 2); ID 2 purchased 3 links to ID 2 Date3 (data 2), etc. So the results looks like below.

Result:

ID  purchased Date
1   5       2017
2   3       2014
3   3       2013
4   3       2015
5   3       2016
6   4       2013
7   4       2013
8   5       2014
9   5       2014
10  4       2016

I was thinking of using couple if statements like below:

if ((Data1$ID== Data2$ID) & Data1$purchased ==3) {
  Data1$Date<- Data2$Date3  
} 

and do the same for purchased 4 and 5... I think i have the wrong approach and appreciate any help! I hope this makes sense. Thank you in advance.

like image 482
wander Hi Avatar asked May 16 '26 03:05

wander Hi


1 Answers

Maybe there is a more beautiful way but you can do like this:

Data1$Date <- ifelse(Data1$purchased==3,Data2$Date3,ifelse(Data1$purchased==4,Data2$Date4,Data2$Date5))

The condition is that your ID are sorted so you don't need to insert the condition on ID in the ifelse statement.

like image 181
Orhan Yazar Avatar answered May 18 '26 00:05

Orhan Yazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!