我确实有以下数据结构:
x <- read.table(header=T, text="
variable class value
a a1 1
a a2 2
a a3 3
b b1 4
b b2 5
b b3 6
c c1 7
c c2 8
c a3 9")
y <- read.table(header=T, text="
a b c
a1 b2 c2
a2 b1 c1
a3 b3 a3"
)
现在我需要将三个变量添加到 df y
-out_a, out_b, out_c
我需要根据列名和类将值映射x$value
到 df 。y
输出应如下所示:
a b c a_out b_out c_out
a1 b2 c3 1 5 8
a2 b1 c1 2 4 7
a3 b3 c2 3 6 9
我可以sqldf
这样做:
sqldf("select y.*, x1.value as a_out , x2.value as b_out, x3.value as c_out
from
y
join x as x1 on (x1.class=y.a and x1.variable='a')
join x as x2 on (x2.class=y.b and x2.variable='b')
join x as x3 on (x3.class=y.c and x3.variable='c')
")
在现实世界中,我有很多专栏(50+),因此我正在寻找更优雅的东西。