Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在一组文件上循环_R_Loops - Fatal编程技术网

R 在一组文件上循环

R 在一组文件上循环,r,loops,R,Loops,我编写了一些代码来查找我所有的.txt文件(它们是ODE模拟的输出),用“read.table”将它们作为数据帧打开,然后对它们执行一些计算 files <- list.files(path="/Users/redheadmammoth/Desktop/Ultimate_Aging_F2016", pattern=".txt",full.names=TRUE) ldf <- lapply(files, read.table) tuse <- se

我编写了一些代码来查找我所有的.txt文件(它们是ODE模拟的输出),用“read.table”将它们作为数据帧打开,然后对它们执行一些计算

files <- list.files(path="/Users/redheadmammoth/Desktop/Ultimate_Aging_F2016",
                pattern=".txt",full.names=TRUE)
ldf <- lapply(files, read.table)
tuse <- seq(from=0,to=100,by=0.1)

for(files in ldf)
  findR <- function(r){
    with(files,(sum(exp(-r*age)*fecund*surv*0.1)-1)^2)
    }
    {
        R0 <- with(files,(sum(fecund*surv*age)))
        GenTime <- with(files,(sum(tuse*fecund*surv*0.1))/R0)
        r <- optimize(f=findR,seq(-5,5,.0001),tol=0.00000001)$minimum
        RV <- with(files,(exp(r*tuse)/surv)*(exp(-r*tuse)*(fecund*surv))) 

plot(log(surv) ~ age,files,type="l")
tmp.lm <- lm(log(surv) ~ age + I(age^2),files) #Fit log surv to a quadratic
lines(files$age,predict(tmp.lm),col="red")
}

files如何使用plyr::ldply()进行此操作。它获取一个列表(在您的例子中是文件列表),并对它们执行相同的功能,然后返回一个数据帧

记住要做的主要事情是为读入的每个文件的ID创建一列,以便知道哪些数据来自哪个文件。最简单的方法就是把它叫做文件名,然后你就可以从那里编辑它了

如果您的函数中有其他参数,它们将跟随您希望在ldply中使用的函数

        # create file list
        files <- list.files(path="/Users/redheadmammoth/Desktop/Ultimate_Aging_F2016",
                            pattern=".txt",full.names=TRUE)
        tuse <- seq(from=0,to=100,by=0.1)

        load_and_edit <- function(file, tuse){
            temp <- read.table(file)

            # here put all your calculations you want to do on each file
            temp$R0 <- sum(temp$fecund*temp$surv*temp*age)

            # make a column for each file name so you know which data comes from which file
            temp$id <- file

            return(temp)
           }


        new_data <- plyr::ldply(list.files, load_and_edit, tuse)
#创建文件列表

这里是答案。这是一个匿名/连续的否决票,所以我删除了它。您的
lappy()
for()
可以组合使用。请出示想要的结果?是否要保存数据帧并绘制线性模型?此外,R0、GenTime、r和RV是每个数据帧中的新列吗?对。是的,我想让它计算那些生命史参数(R0等),然后在每个数据帧上将它们保存为一个新列。我想保存每个数据帧并绘制一个线性模型。我最终使用的解决方案与您的非常相似!谢谢你这么快的回复。。。在计算完所有数据后,它可以很方便地绘制出所有118个实验结果。现在让我想想如何给你的答案投票;)