kin182
kin182

Reputation: 403

How to match columns from one list to another?

I am new to R and I have a question about matching columns of data frames in one list based on row names from another list. For example:

list1 = list(mtcars[1:10,],mtcars[11:20,])
list2 = list(mtcars[1:10,1:4],mtcars[11:20,1:4])

I would like to match column drat to list2 based on the common row names of list1 and list2. I did something like:

drat = lapply(list1, function(x) setNames(x$drat, rownames(x)))
lapply(list2, function(x) {x$drat = drat[as.character(rownames(x))]; x})

But it did not work, returning

[[1]]
                   mpg cyl  disp  hp drat
Mazda RX4         21.0   6 160.0 110 NULL
Mazda RX4 Wag     21.0   6 160.0 110 NULL
Datsun 710        22.8   4 108.0  93 NULL
Hornet 4 Drive    21.4   6 258.0 110 NULL
Hornet Sportabout 18.7   8 360.0 175 NULL
Valiant           18.1   6 225.0 105 NULL

[[2]]
                     mpg cyl  disp  hp drat
Merc 280C           17.8   6 167.6 123 NULL
Merc 450SE          16.4   8 275.8 180 NULL
Merc 450SL          17.3   8 275.8 180 NULL
Merc 450SLC         15.2   8 275.8 180 NULL
Cadillac Fleetwood  10.4   8 472.0 205 NULL
Lincoln Continental 10.4   8 460.0 215 NULL

Could anyone help? Thanks!

Upvotes: 2

Views: 86

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48191

Here's a base R approach:

mapply(merge, lapply(list1, `[`, "drat"), list2,
       MoreArgs = list(by = "row.names"),
       SIMPLIFY = FALSE)
# [[1]]
#            Row.names drat  mpg cyl  disp  hp
# 1         Datsun 710 3.85 22.8   4 108.0  93
# 2         Duster 360 3.21 14.3   8 360.0 245
# 3     Hornet 4 Drive 3.08 21.4   6 258.0 110
# 4  Hornet Sportabout 3.15 18.7   8 360.0 175
# 5          Mazda RX4 3.90 21.0   6 160.0 110
# 6      Mazda RX4 Wag 3.90 21.0   6 160.0 110
# 7           Merc 230 3.92 22.8   4 140.8  95
# 8          Merc 240D 3.69 24.4   4 146.7  62
# 9           Merc 280 3.92 19.2   6 167.6 123
# 10           Valiant 2.76 18.1   6 225.0 105
# 
# [[2]]
#              Row.names drat  mpg cyl  disp  hp
# 1   Cadillac Fleetwood 2.93 10.4   8 472.0 205
# 2    Chrysler Imperial 3.23 14.7   8 440.0 230
# 3             Fiat 128 4.08 32.4   4  78.7  66
# 4          Honda Civic 4.93 30.4   4  75.7  52
# 5  Lincoln Continental 3.00 10.4   8 460.0 215
# 6            Merc 280C 3.92 17.8   6 167.6 123
# 7           Merc 450SE 3.07 16.4   8 275.8 180
# 8           Merc 450SL 3.07 17.3   8 275.8 180
# 9          Merc 450SLC 3.07 15.2   8 275.8 180
# 10      Toyota Corolla 4.22 33.9   4  71.1  65

I use maple element-wise on list2 and the column drat of each list1 element. The function applied by mapply is merge, where I specify to do that by row names, and prohibit converting the result to an array by setting SIMPLIFY to FALSE. A side effect is that the resulting data frames contain a Row.names column.

Upvotes: 4

Related Questions