【发布时间】:2013-07-09 13:58:51
【问题描述】:
我确实有以下数据结构:
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+),因此我正在寻找更优雅的东西。
【问题讨论】:
标签: r