循环纵向数据集级别

时间:2016-03-14 17:04:42

标签: r function loops

我试图在以下3个年龄组中的4个地区中选择ID(患者): 2 - < 4 yrs,4 - < 6 yrs,6 - < 8 yrs。数据是下面代码中给出的longData。我只需要选择符合这些年龄标准的一半ID,并将它们合并到一个单独的数据框中。 我已经编写了一个函数(subsetFunc)来为每个区域单独执行此操作,但我希望我可以编写代码 使用for循环应用类似的函数从所有四个区域获取此信息作为单独的数据帧(而不是为每个区域应用代码4次)。我可以简单地应用函数12次然后rbind每个输出但这似乎重复。 在我的真实数据集中,我有几个区域,因此将这个函数应用60次会太繁琐。此外,这是 写作函数的重点 - 自动化重复的事物。

library(dplyr)
roundUp <- function(x) trunc(x+0.5)

set.seed(2016)

longData <- data.frame(patient=rep(paste(letters[1:20], sep = "_", 1:20), each=5), 
                   age=rep(runif(20, 1, 10), each = 5),var=runif(100, 50, 1000),
                   time=rep(1:5, 20), region = rep(c("EUROPE", "AFRICA", "ASIA",
                                                     "OCEANIA"), c(25, 25, 25, 25)))

subsetFunc <- function(df, group_in, seedNumb, a, b){

data <- filter(df, region == group_in, age >= a, age < b)
set.seed(seedNumb)
n <- roundUp(
data%>% filter(!duplicated(data["patient"])) %>% nrow()/2)
ids <- sample_n(unique(data[, c("patient", "region")]), n)$patient
fd <- data[data$patient %in% ids, ]
return(fd)

}

# this gives half of the children in Europe between ages 2 and < 4 yrs
subsetFunc(longData, "EUROPE", 1, 2, 4)

# Desired Output (tedious method for doing this)


# 2-<4
d_1  <- subsetFunc(longData, "EUROPE", 1, 2, 4)
d_2 <- subsetFunc(longData, "ASIA", 1, 2, 4)
d_3 <- subsetFunc(longData, "OCEANIA", 1, 2, 4)
d_4 <- subsetFunc(longData, "AFRICA", 1, 2, 4)

# 4- < 6
d_5 <- subsetFunc(longData, "EUROPE", 1, 4, 6)
d_6 <- subsetFunc(longData, "ASIA", 1, 4, 6)
d_7 <- subsetFunc(longData, "OCEANIA", 1, 4, 6)
d_8 <- subsetFunc(longData, "AFRICA", 1, 4, 6)

# 6- 8
d_9 <- subsetFunc(longData, "EUROPE", 1, 6, 8)
d_10 <- subsetFunc(longData, "ASIA", 1, 6, 8)
d_11 <- subsetFunc(longData, "OCEANIA", 1, 6, 8)
d_12 <- subsetFunc(longData, "AFRICA", 1, 6, 8)

finalLongData <- rbind(d_1, d_2, d_3, d_4, d_5, d_6, d_7, d_8, d_9,
                    d_10, d_11, d_12)

我开始写下以下内容:

for (i in levels(longData$cohort)){

dFrame <- subsetFunc(longData, i, 1, a = 0, b = 2)
return(dFrame)
}

我现阶段有点陷入困境,因此非常感谢任何协助。

1 个答案:

答案 0 :(得分:2)

好吧,我回到这个帖子,我想我可能已经破解了它。首先,我需要重新定义您的subsetFunc函数:

subsetFunc <- function(df, seedNumb, a, b){
  data <- filter(df,  age >= a, age < b)
  set.seed(seedNumb)
  n <- ceiling(
    data%>% filter(!duplicated(data["patient"])) %>% nrow()/2)
  ids <- sample_n(unique(data[, c("patient", "region")]), n)$patient
  fd <- data[data$patient %in% ids, ]
  return(fd)
}

然后,我能够将所有结果放在一起,而不必使用尽可能多的行:

LongDataFinal <- 
do.call('rbind', 
           as.list(sapply(c(2,4,6), FUN = function(y) 
                   by(longData, longData$region, 
       FUN = function(x) subsetFunc(df = x, seedNumb = 1, a = y, b = y+2)))))