如何输出每个循环向量

时间:2018-08-20 03:36:01

标签: r for-loop

有5个人数据(主题1,3,5,7,9),

我按块的条件将其子集  (区块(1:12),区块(51:62),区块(101:112)),

输出我确切想要的值----'Respond',我用它来计算其他东西。

这是主题1的示例,


[

respond	Subject	Session	Block
3.00 	1	1	1
2.00 	1	1	2
3.00 	1	1	3
3.00 	1	1	4
2.00 	1	1	5
3.00 	1	1	6
1.00 	1	1	7
3.00 	1	1	8
1.00 	1	1	9
2.00 	1	1	10
3.00 	1	1	11
1.00 	1	1	12
2.00 	1	1	51
2.00 	1	1	52
2.00 	1	1	53
1.00 	1	1	54
3.00 	1	1	55
2.00 	1	1	56
2.00 	1	1	57
3.00 	1	1	58
2.00 	1	1	59
3.00 	1	1	60
1.00 	1	1	61
1.00 	1	1	62
3.00 	1	1	101
1.00 	1	1	102
3.00 	1	1	103
1.00 	1	1	104
2.00 	1	1	105
3.00 	1	1	106
2.00 	1	1	107
1.00 	1	1	108
3.00 	1	1	109
3.00 	1	1	110
2.00 	1	1	111
1.00 	1	1	112

] 1


最后,它将像每个主题的矩阵一样呈现(5)

(block1:12--respond)  
3.00    
2.00 
3.00 
3.00 
2.00 
3.00 
1.00 
3.00 
1.00 
2.00 
3.00 
1.00 

 (block51:62--respond) 
 2.00 
2.00 
2.00 
1.00 
3.00 
2.00 
2.00 
3.00 
2.00 
3.00 
1.00 
1.00 

 
 (block101:112--respond)  
3.00 
1.00 
3.00 
1.00 
2.00 
3.00 
2.00 
1.00 
3.00 
3.00 
2.00 
1.00 


编程(1)

subject <- c(1,3,5,7,9)
for i in length (subject) {
     data(i)<- list(
          sub_1_RT<-subset(data, subject == i & block ==(1:12),'Respond'),
          sub_2_RT<-subset(data, subject == i & block ==(51:62),'Respond'),             
  )
  print(data)
}

编程2

 for (i in c(1,3,5,7,9)) {
   mydata<- list(
                sub_1 <- subset(sub45,sub45$Subject == 'i' 
                         & sub45$Session == '1'
                         & sub45$Block == (1:12),'Respond'),
                sub_2 <- subset(sub45,sub45$Subject == 'i' 
                         & sub45$Session == '1'
                         & sub45$Block == (51:62),'Respond'),

   )
   print(mydata)
}

1 个答案:

答案 0 :(得分:1)

我需要为自己创建一个示例数据集,以便我可以在其上运行代码(您可以忽略此行)。

blocks<-cbind((1:12),(51:62),(101:112))
dt<-data.frame(Respond= sample(1:3,112,replace = T),Subject=sample(1:10,112,replace = T),
               Session=sample(1:4,112,replace = T), Block=sample(blocks, 112,replace = T ))

然后subset

print("block: 1:12--respond")
 subset(dt, Subject  %in% c(1,3,5,7,9) & Block %in% (1:12), Respond   ) 
print("block: 51:62--respond")
 subset(dt, Subject  %in% c(1,3,5,7,9) & Block %in% (51:62), Respond   )
print("block101:112--respond")
 subset(dt, Subject  %in% c(1,3,5,7,9) & Block %in% (101:112), Respond   )