我有下表:
table(dta$recipient,dta$treat)>0
1 2 3 4 5 6
couple TRUE TRUE FALSE FALSE FALSE FALSE
female FALSE FALSE TRUE TRUE FALSE FALSE
male FALSE FALSE FALSE FALSE TRUE TRUE
我还有一个变量dta $ treat_new,其中包含dta $ treat的排列。如何使用收件人的相应值创建变量dta $ recipient_new?请注意,级别(dta $ recipient)和级别(dta $ treat)可能会更改。所以预期的输出将是一个新的变量,如dta $ recipient:
> head(dta$recipient_new)
[1] male female male couple male male
Levels: couple female male
对应于dta $ treat_new
> head(dta$treat_new)
[1] 5 3 6 1 5 6
这是一个可重复的例子:
set.seed(12345)
recipient <- rep(c("male","female"), times=2)
treat <- rep(1:4, times=2)
df <- data.frame(recipient,treat)
table(df$recipient, df$treat)
df$treat_perm <- sample(treat)
df$treat_perm
[1] 2 3 1 4 2 1 3 4
我想知道如何获得相应的收件人,所以:
df$recipient_perm
[1] female male male female female male male female