多个交替条件的{ifelse语句

时间:2016-05-08 07:13:03

标签: r

我的数据涉及在几个条件下收集的因变量(DV)的实验,其结构如下:

AnalysedData <- data.frame(Participant = c("Bill", "Bill", "Bill", "Harry", "Harry", "Harry", "Paul", "Paul", "Paul"),
                           Code = c(1, 1, 1, 2, 2, 2, 1, 1, 1),
                           Condition = c("Con", "Expr", "Plac", "Con", "Expr", "Plac", "Con", "Expr", "Plac"),
                           DV = c(26.07, 26.06, 26.05, 26.09, 26.04, 26.65, 26.64, 26.62, 26.63))

所有参与者都接受了相同的条件,但是以随机顺序完成了两个条件 - 控制条件总是先进行。那些完成实验(Expr)条件作为第二次试验的人的Code为1,而完成安慰剂(Plac)作为第二次试验的人则为{{1}的2 }}

我希望添加一个新列Code,其中包括每个参与者的试验顺序。我的首选输出是:

AnalysedData$Trial

Harry完成安慰剂条件的首选输出地址第二,实验条件第三,给他AnalysedData <- data.frame(Participant = c("Bill", "Bill", "Bill", "Harry", "Harry", "Harry", "Paul", "Paul", "Paul"), Code = c(1, 1, 1, 2, 2, 2, 1, 1, 1), Condition = c("Con", "Expr", "Plac", "Con", "Expr", "Plac", "Con", "Expr", "Plac"), DV = c(26.07, 26.06, 26.05, 26.09, 26.04, 26.65, 26.64, 26.62, 26.63), Trial = c(1, 2, 3, 1, 3, 2, 1, 2, 3)) 。相比之下,比尔和保罗都完成了实验条件第二和安慰剂条件第三,给出了c(1, 3, 2)。如上所述,这个替代序列由c(1, 2, 3)表示,比尔和保罗等于1,哈利为2。

我知道我可以使用以下内容包含1来指定完成的第一个试验(Code为所有参与者):

Con

如何针对多种情况完成上述操作?

2 个答案:

答案 0 :(得分:1)

结合使用ifelseas.integer(或as.numeric)和factor,您可以利用因子变量存储为带标签的整数这一事实: / p>

AnalysedData$Trial <- ifelse(AnalysedData$Code==1, 
                             as.integer(factor(AnalysedData$Condition, 
                                               levels = c("Con", "Expr", "Plac"))),
                             as.integer(factor(AnalysedData$Condition, 
                                               levels = c("Con", "Plac", "Expr"))))

你得到:

> AnalysedData
  Participant Code Condition    DV Trial
1        Bill    1       Con 26.07     1
2        Bill    1      Expr 26.06     2
3        Bill    1      Plac 26.05     3
4       Harry    2       Con 26.09     1
5       Harry    2      Expr 26.04     3
6       Harry    2      Plac 26.65     2
7        Paul    1       Con 26.64     1
8        Paul    1      Expr 26.62     2
9        Paul    1      Plac 26.63     3

答案 1 :(得分:0)

这应该有效:

AnalysedData$Trial <- ifelse(AnalysedData$Condition == "Con", 1, 0)

index<-AnalysedData$Condition == "Plac"

AnalysedData$Trial[index]<-rep(2,sum(index))