arielle arielle - 1 month ago 6
R Question

R: Applying a function on data frame columns defined in another table

I have a dataframe (df) that looks like this:

A B C D E F G H
a 1 2 3 4 5 3 4 2
b 3 4 5 5 4 5 5 4
c 1 4 6 7 9 6 7 4
d 2 4 5 7 8 5 7 4
e 2 2 4 5 7 4 5 2


I would like to compute the ratio of different columns, based on a table like this, that indicates which column needs to be the numerator and denominator:

num denom
A E
B G
F C
H D


So for example the first column in the output will be column A divided by column E.

The output would look like this (I want to keep the column names of the numerators):

A B F H
a 0.2 0.5 1 0.5
b 0.75 0.8 1 0.8
c 0.111111111 0.571428571 1 0.571428571
d 0.25 0.571428571 1 0.571428571
e 0.285714286 0.4 1 0.4


I hope I am making this understandable, here is the dput of the original table:

structure(list(A = c(1L, 3L, 1L, 2L, 2L), B = c(2L, 4L, 4L, 4L,
2L), C = c(3L, 5L, 6L, 5L, 4L), D = c(4L, 5L, 7L, 7L, 5L), E = c(5L,
4L, 9L, 8L, 7L), F = c(3L, 5L, 6L, 5L, 4L), G = c(4L, 5L, 7L,
7L, 5L), H = c(2L, 4L, 4L, 4L, 2L)), .Names = c("A", "B", "C",
"D", "E", "F", "G", "H"), class = "data.frame", row.names = c("a",
"b", "c", "d", "e"))


Any help will be much appreciated! Thanks

Answer

Here we go:

mdf <- data.frame(num=c("A", "B", "F", "H"), denom=c("E", "G", "C", "D"), stringsAsFactors = F)
df_num <- df[, mdf$num]
df_denom <- df[, mdf$denom]
df_num/df_denom

The stringAsFactors = Fis important...