为每位受试者分配治疗方法

时间:2018-11-14 07:32:58

标签: r loops

我有四个阶层(stratum1stratum2stratum3stratum4),我想在循环中为每个阶层执行此代码并添加变量到数据帧

Strat1_Stratum1_Treat <- block_ra(blocks = ProjectData1$Stratum1,
                                  prob = .5, conditions = c("A","B"))

check the nature of the data

1 个答案:

答案 0 :(得分:0)

示例数据

blocks <- sample(0:1, 40, TRUE)
data <- as.data.frame(matrix(blocks, 10, 4))
data

#    V1 V2 V3 V4
# 1   0  1  1  1
# 2   0  0  0  0
# 3   1  1  0  1
# 4   0  0  0  1
# 5   1  1  1  1
# 6   1  1  0  1
# 7   0  0  0  0
# 8   1  0  0  0
# 9   0  0  1  0
# 10  0  0  0  0

使用lapply()为每个变量执行一个函数。

data[5:8] <- lapply(data, block_ra, prob = .5, conditions = c("A", "B"))
data

#    V1 V2 V3 V4 V1.1 V2.1 V3.1 V4.1
# 1   0  1  1  1    A    A    B    B
# 2   0  0  0  0    B    B    B    B
# 3   1  1  0  1    A    A    A    A
# 4   0  0  0  1    B    A    B    B
# 5   1  1  1  1    B    B    A    A
# 6   1  1  0  1    A    B    B    A
# 7   0  0  0  0    B    A    B    A
# 8   1  0  0  0    B    B    A    B
# 9   0  0  1  0    A    A    B    A
# 10  0  0  0  0    A    B    A    B