一种可能的替代解决方案是将查找表与数据框连接起来:
1.一些示例数据(与@chl 在他的答案中使用的相同,但使用数据框而不是查找值列表):
lut <- data.frame(Target=1:5, Size=c("L","M","L","S","L"), Color=c("R","B","G","B","R"))
df1 <- data.frame(rep(1:2, each=2), c("A","D","A","B"),
c(5,2,1,5), c(2,4,4,8), c(8,6,6,3))
names(df1) <- c("user", "condition", 1:3)
2.使用data.table包,您可以将数据帧转换为data.table和长格式(与reshape2相同)
dt.melt <- melt(setDT(df1), id=c("user","condition"),
variable.factor = FALSE)[, variable := as.numeric(variable)]
3.与查找表连接,以便将 和 的匹配值添加Size
到Color
长data.table:
dt.melt[lut, on = c("variable" = "Target"), nomatch=0]
或者:
lut[dt.melt, on = c("Target" = "variable")]
这两者都导致:
user condition variable value Size Color
1: 1 A 1 5 L R
2: 1 D 1 2 L R
3: 2 A 1 1 L R
4: 2 B 1 5 L R
5: 1 A 2 2 M B
6: 1 D 2 4 M B
7: 2 A 2 4 M B
8: 2 B 2 8 M B
9: 1 A 3 8 L G
10: 1 D 3 6 L G
11: 2 A 3 6 L G
12: 2 B 3 3 L G
您也可以一次调用将其绑定在一起:
dt.melt <- melt(setDT(df1), id=c("user","condition"),
variable.factor = FALSE)[, variable := as.numeric(variable)
][lut, on = c("variable" = "Target"), nomatch=0]
通过dplyr和tidyr的组合,您可以实现相同的效果:
library(dplyr)
library(tidyr)
df.new <- df1 %>%
gather(variable, value, -c(1:2)) %>%
mutate(variable = as.numeric(as.character(variable))) %>%
left_join(., lut, by = c("variable" = "Target"))
这将给出相同的结果:
> df.new
user condition variable value Size Color
1 1 A 1 5 L R
2 1 D 1 2 L R
3 2 A 1 1 L R
4 2 B 1 5 L R
5 1 A 2 2 M B
6 1 D 2 4 M B
7 2 A 2 4 M B
8 2 B 2 8 M B
9 1 A 3 8 L G
10 1 D 3 6 L G
11 2 A 3 6 L G
12 2 B 3 3 L G