1

I have two dataframes. One that has a list of unique ID numbers (think customer names and demographic data) and another dataframe with a list of transaction data (think purchase data, $ amount, etc) where the same unique ID number is also a column.

I'd like to create a dummy variable using a nested ifelse statement that searches the transaction dataframe using the unique ID and then check if a second attribute matches between the two dataframes.

For example:

data.frame3$dummy_variable <- ifelse(data.frame1$id == data.frame2$id,
ifelse(data.frame1$attributeX == data.frame2$attritubeX, 1, 0)
,2)

However, data.frame1 and data.frame2 have different row lengths, so I get an error message: "longer object length is not a multiple of shorter object length".

These data.frames cannot be the same length. Is there another way to attack this?

Adam D
  • 31
  • 3
  • Might be easier to just merge the 2 dataframes based on ID and then making those checks. – Jason V Apr 09 '15 at 04:17
  • 1
    It seems like a complex thing to try to do in 1 step. I agree with Jason; why not merge your 2 dfs first and then check whether other columns match? Another approach would be to use loops, but most R programmers frown uppon them, for various reasons, valid or not. I still use loops to solve a lot of problems, and this is one where they _could_ be useful. But I'd go with merging first. – Dominic Comtois Apr 09 '15 at 04:29
  • @DominicComtois I was hoping to avoid using a merge because I need to create dummy variables based on many different combinations (e.g. ID == ID and AttributeX == AttributeX, where X is any number of 15 attributes). Could I get the ifelse function to work if I added fake rows to one dataframe to make it equal length to the other? – Adam D Apr 09 '15 at 19:46
  • Well, it would make the code work without errors, but it would _not_ do what you'd expect it to do. If you had for instance an ID `123` on the first line and that same ID on your 2nd dataframe is on line 2, they'll never be considered as "one entity" by your code. Trust me, merging will save you a lot of trouble! – Dominic Comtois Apr 09 '15 at 23:17
  • Possible duplicate of [How to join (merge) data frames (inner, outer, left, right)?](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right) – divibisan Mar 04 '19 at 16:41

0 Answers0