一种可能的替代办法是将研究表与数据框架结合起来:
<>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. with the data.table package you can transform the dataframe to a data.table and to long format (which works the same as with 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]
or:
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]
With the combination of dplyr and tidyr you can achieve the same:
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