I want to match two data frames based on their IDs and append the repeated selection into a single list. Examples of the data frames I have are as below:
df1 = data.frame(ID = c("A", "B", "C", "D"), count = c(4, 6, 7, 8))
df2 = data.frame(ID = c("A", "B", "C", "D"), direction = c("up", "down", "up", "up"), reference = c(38, 39, 40, 40))
The two data frames look something like this:
| ID | count |
|---|---|
| A | 4 |
| B | 6 |
| C | 7 |
| D | 8 |
| ID | direction | reference |
|---|---|---|
| A | up | 38 |
| A | down | 39 |
| C | up | 40 |
| D | up | 40 |
Essentially, I want the final result to look like this, where the information from the df2 can be merged with df1 but with details concatenated into a single list and if multiple corresponding entries were found in df2, they can be stored as a list of lists:
| ID | count | Info |
|---|---|---|
| A | 4 | c(up = 38, down = 39) |
| B | 6 | NA |
| C | 7 | c(up =40) |
| D | 8 | c(up =40) |
I have tried merging two data frames, but this will result in multiple entries repeated as a new row. I'm considering trying to parse through the second data frame for a match as I did with the database environment previously, but I would appreciate it if you can let me know how to do such using data frame instead of environment. Of course, if there's a more efficient approach to this, that would be much appreciated too! Example of what I did to match df1 onto a database environment:
i=1
for (row in 1:nrow(df)){
tmp <- paste(df$ID[i])
tmp2 <- as.list(mget(tmp, mirbaseID2ACC, ifnotfound = NA))
if (is.na(tmp2) == TRUE) {
tmp <- paste(df$simpleID[i])
tmp2 <- as.list(mget(tmp, mirbaseID2ACC, ifnotfound = NA))
}
if (i<(nrow(df)+1)) {
df$ACCESSION[i] <- tmp2
i=i+1
}
}
*Note that the "simple" column is there for the actual data frame because the samples have a very specific ID (ie A-ab-2) but for the purpose of this example, we can assume that the ID itself is simple enough to be detected with the data frame I'm trying to