如何重复R中的代码以满足重复条件

时间:2018-04-08 17:43:55

标签: r conditional-statements repeat

我需要重复一次代码24次(针对24个不同的参与者),确保每个试用路由中的每个 Scene2 整体em>,我在每个参与者的列 Random 中有相同数量的1和0(即 Part.1 Part.2 第3部分等)当目标等于0时。

以下是我正在使用的代码:

Scene2 = rep(c(1:10), times=9)
myDF2 <- data.frame(Scene2)
myDF2$Target <- rep(0,10, each=9)
myDF2$Target[myDF2$Scene2==7] <- 1
myDF2$Trial <- rep(c(1:9),each=10)
myDF2$Route <- rep(LETTERS[1:6], each=10, length=nrow(myDF2))

library(plyr)
myDF3 <- myDF2 %>% group_by(Trial, Route) %>%  mutate(Random = ifelse(myDF2$Target==0,sample(c(rep(0,5),rep(1,5))),1)) %>% as.data.frame()

我需要获得这样的东西:

Scene2  Target  Trial   Route   Part.1  Part.2  Part.3  Part.4  …   Part.24 Tot.1   Tot.0
1       0       1       A       0       1       1       0           0       12      12
2       0       1       A       1       0       1       0           0       12      12
3       0       1       A       1       0       0       0           0       12      12
4       0       1       A       0       1       0       1           0       12      12
5       0       1       A       1       0       1       1           0       12      12
6       0       1       A       1       0       0       0           1       12      12
7       1       1       A       1       1       1       1           1       24      0
8       0       1       A       0       0       1       1           1       12      12
9       0       1       A       0       1       1       1           1       12      12
10      0       1       A       0       1       0       0           1       12      12

如何实现这一目标?任何建议都将非常感谢。

1 个答案:

答案 0 :(得分:0)

由于这里的某些条件逻辑需要满足特定的规范,我认为这对函数来说更容易。

Scene2 = rep(c(1:10), times=9)
myDF2 <- data.frame(Scene2)
myDF2$Target <- rep(0,10, each=9)
myDF2$Target[myDF2$Scene2==7] <- 1
myDF2$Trial <- rep(c(1:9),each=10)
myDF2$Route <- rep(LETTERS[1:6], each=10, length=nrow(myDF2))

library(tidyverse)

fill_random_columns <- function(df, reps) {

    # Start a loop with a counter
    for (i in 1:reps) {
    # Create a vector of 1s and 0s for filling rows    
    bag <- c(rep(0, 12), rep(1, 12))
    # Build up conditional data frame of 1s and 0s   
    row_vector <- as.data.frame(t(sapply(df$Target, function(v) {
        if (v == 1) return(rep(1, reps))
        else (return(sample(bag, reps)))
        })))
    }
    # Create column names
    colnames <- lapply(1:reps, function(i) {paste0("Part.", i)})
    # Name columns and sum up rows
    row_vector <- row_vector %>%
        `colnames<-`(colnames) %>%
        mutate(Total = rowSums(.))
    # Attach to original data frame
    df <- bind_cols(df, row_vector)
    return(df)
}

myDF3 <- myDF2 %>%
    group_by(Trial, Route) %>%
    fill_random_columns(., 24)