0
votes

I have three tables that I'm attempting to merge into one.

The main table is similar to:

Table1 <- data.frame("Data" = c(1, 2, 3, 4, 5), "Desc" = c("A", "A", "A", "B", "B"))

TableA <- data.frame("Values" = c(6, 2, 3))

TableB <- data.frame("Values" = c(2, 7))

I want to add another column to Table1 with the values from TableA and TableB, but Values coming from TableA must be placed in a row containing "A" in the "Desc" column and TableB values in rows containing "B" in the "Desc" column. The number of rows in Table A equal the number of rows Table1 with "A" and same for TableB.

The resulting Table should look like:

Table1 <- data.frame("Data" = c(1, 2, 3, 4, 5), "Desc" = c("A", "A", "A", "B", "B"), "Values" = c(6, 2, 3, 2, 7))

> Table1
  Data Desc Values
1    1    A      6
2    2    A      2
3    3    A      3
4    4    B      2
5    5    B      7
2

2 Answers

1
votes

First note that these are "data.frames", not "tables". A "table" is actually a different class in R and they aren't the same thing. This strategy should work

Table1$Values <- NA

Table1$Values[Table1$Desc=="A"] <- TableA$Value
Table1$Values[Table1$Desc=="B"] <- TableB$Value

Table1
#   Data Desc Values
# 1    1    A      6
# 2    2    A      2
# 3    3    A      3
# 4    4    B      2
# 5    5    B      7
0
votes

If you have multiple Table (TableA, TableB, TableC,...etc) and if you need to match the suffix of Table. to Table1 column Desc

ls1 <- ls(pattern="Table")
ls1
#[1] "Table1" "TableA" "TableB"
library(stringr)
indx <- str_extract(ls1[-1], perl('(?<=Table)[A-Z]'))
lst1 <- mget(ls1[-1])

do.call(rbind,
  lapply(seq_along(lst1),function(i) {
               x1 <- lst1[[i]]
               x2 <- Table1[!is.na(match(Table1$Desc, indx[i])),]
               x2$Values <- x1$Values
               x2}
  ))
 #  Data Desc Values
 #1    1    A      6
 #2    2    A      2
 #3    3    A      3
 #4    4    B      2
 #5    5    B      7
  • In the first step, after I created the objects (Table.), looked for the object names ls(pattern="Table")
  • Extracted the suffix LETTERS A, B from the objects that needs to be matched. Used regex lookbehind i.e. (?<=Table)[A-Z] matches a substring (uppercase letter) preceded by the string Table and extract the substring.
  • mget returns the value of the objects as a list
  • Loop using lapply. Match the Desc column in Table1 with the extracted suffix and created a new column