一種可能的替代解決方案與所述數據幀加入查找表:
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和長格式(其中W獸人一樣與reshape2)
dt.melt <- melt(setDT(df1), id=c("user","condition"),
variable.factor = FALSE)[, variable := as.numeric(variable)]
以的Size
和Color
匹配值添加到長數據與查表加入。表:
dt.melt[lut, on = c("variable" = "Target"), nomatch=0]
或:
lut[dt.melt, on = c("Target" = "variable")]
結果是既:
dt.melt <- melt(setDT(df1), id=c("user","condition"),
variable.factor = FALSE)[, variable := as.numeric(variable)
][lut, on = c("variable" = "Target"), nomatch=0]
:
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
您也可以集中在一個調用綁定此10
隨着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
所以,在第一行的第二表, '1 A 5,2'表示對象1對於Size = L/Color = R得分爲5,對於Size = M/Color = B得分爲2,對嗎? – chl
對,在條件A下,但可能有多個Size = M和Color = B的目標。例如,目標20也可能是中等和藍色。 – Justin