2017-10-15 114 views
-1

我大家!For循环和功能错误与R

我发现了我的博士研究生的世界,当我想要实现循环来简化分析时,我遇到了一些问题。

我的数据帧是:

'data.frame': 3581 obs. of 8 variables: 
$ Date   : Factor w/ 7 levels "03-03-17","10-02-17",..: 
$ Experimentator: Factor w/ 9 levels "BURLET","DECHAUD",..: 
$ Origin  : Factor w/ 3 levels "FRANCE","JAPAN",..: 
$ City   : Factor w/ 6 levels "MONTPELLIER",..: 
$ Lineage  : Factor w/ 27 levels "L21","L22","L26",..: 
$ Sex   : Factor w/ 2 levels "Female","Male": 
$ ccr   : int 1183 1813 1866 1745 1210 1463 2477 1506 

前6是我的因素和最后我的定量变量。 我需要在同一时间几个因素的工作,然后当我想做例如shapiro.test: 由:

by(data$ccr, c(data$Date, data$Sex, data$Lineage), shapiro.test()) 
Error in tapply(seq_len(3581L), list(`c(data$Date, data$Sex, 
data$Lineage)` = c(2L, : the arguments must have the same length 

有了一个for循环很难给我,让我试着写:

for(sex in levels(data$Sex)){ 
    for(date in levels(data$Date)){ 
    for(lineage in levels(data$Lineage)){ 
     shapiro.test(data$ccr[,lineage]) 
    } 
    } 
} 

BU我不知道如何来增加我的环...

感谢您的帮助!

+0

接收数据你至少应该告诉我们你在使用它在这里封装(S)。 –

+0

您需要所有3581条记录? –

+1

在'by'中,分组变量('INDICES')应该是“一个_'列表因素”。比较'(mtcars,c(mtcars $ vs,mtcars $ am),function(dat)shapiro.test(dat $ mpg))''(您的情况),'by(mtcars,list(mtcars $ vs,mtcars $ am),函数(dat)shapiro.test(dat $ mpg))'。 – Henrik

回答

0

您可以使用索引来这样

index <- 1 

while(index != 3582){ 
    for(sex in levels(data$Sex)){ 
    for(date in levels(data$Date)){ 
     for(lineage in levels(data$Lineage)){ 
     shapiro.test(data$ccr[,lineage]) 
     index <- index + 1 
     } 
    } 
    } 
} 
1

for循环运行是没有必要为此在R.我不使用by()功能是最好的办法要么认为。最简单的方法是使用dplyr基础设施:

library(dplyr)

data %>% 
    group_by(Sex, Date, Lineage) %>% 
    filter(n() > 2) %>% 
    summarise(shapiro_pvalue = shapiro.test(ccr)$p.value, 
      shapiro_stat = shapiro.test(ccr)$statistic) 

filter(n() > 2)处理的事实,shapiro.test至少需要3个样品进行计算。 (贷Rui Barradas为重复性好例子!)

dplyrbase R完全不同的,但如果你开始你的博士论文,并需要使用R,它,如果你想使你的生活更简单使用它是值得的。

0

你可以使用base R来代替by使用split/lapply
首先,一些虚假的数据,其名称更改为dat,因为data已经是R函数。

set.seed(9235) # make it reproducible 
n <- 3581 
d <- seq(as.Date("2017-01-01"), as.Date("2017-12-31"), by = "day") 
d <- format(d, "%d-%m-%y") 
dat <- data.frame(
    Date = sample(d, n, TRUE), 
    Experimentator = sample(LETTERS[1:9], n, TRUE), 
    Origin = sample(LETTERS[11:13], n, TRUE), 
    Lineage = sample(paste0("L", 1:27), n, TRUE), 
    Sex = sample(c("F", "M"), n, TRUE), 
    ccr = sample(3000, n, TRUE) 
) 

现在的代码。需要注意的是shapiro.test只有number of non-missing values must be between 3 and 5000.

sp <- split(dat$ccr, list(dat$Date, dat$Sex, dat$Lineage)) 
sp <- sp[which(sapply(sp, function(x) length(x) > 2))] 

result <- lapply(sp, shapiro.test)