R - 如何将循环转换为R中的函数 [英] R - How to turn a loop to a function in R

查看:149
本文介绍了R - 如何将循环转换为R中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的阅读。我经常发现我需要将一个函数应用于我的数据切片,然后绑定输出。我通常会为此目的构建一个循环,但我确信我做错了,在R中我应该使用不同的思维方式。你能帮助我学习更好的方法吗?

Thank you for your reading. I often find that I need to apply a function to slices of my data, and then bind the outputs. I usually build a loop for that purpose, but I am sure I am doing it wrong, and that in R I should be using a different way of thinking. Can you please help me learn a better way to do this?

谢谢,

adam

    rm(m); m=0; # this variable will hold the output of the loop
    for (nobs in as.numeric(levels(factor(s1$obs)))) { # go over observer index
       for (nses in as.numeric(levels(factor(subset(s1, obs==nobs)$session)))) { # go over session index
          ns1=subset(s1, obs== nobs & session==nses & ky %in% c(1,2)); # the data slice of interest
          ds=round( clfdMc (ns1),2); cs=round( cfdMc (ns1),2); # apply function to data slice
          rw=cbind(nobs,nses,ds[2,3],ds[3,3],ds[2,3]-ds[3,3], cs[1,3],cs[2,3],nobs+nses/10, ds[2,4],ds[3,4],cs[1,4],cs[2,4]) # create a row from function output
          m=rbind(m,rw); #print(paste('obs:',nobs,' nses:',nses,'clear d:',ds[2,3],'red d',ds[3,3]))# bind new row to previous rows
        }
    }

m=data.frame(m[2:dim(m)[1],]) # create a data frame from these results
names(m)=c('obs','ses','D_clear','D_red','diffD','D_cg-1','D_cg+1','mark','C_clear','C_red','C_cg-1','C_cg+1') # give names to column variables


推荐答案

plyr 包专门用于处理像这样的数据操作问题。查看网页上的一些文档: http://had.co.nz/plyr/

The plyr package was built specifically to deal with data manipulation problems like this. Check out some of the documentation on the webpage: http://had.co.nz/plyr/

我并不完全理解您使用的 round()语法,但我认为相当于 plyr 电话会是

I don't exactly understand the round() syntax you used, but I believe an equivalent plyr call would be

library(plyr)
ddply(s1, .(obs, session), transform, ds = round(clfdMc, 2), cs = round(cfdMc, 2))

我不是完全确定这会做你想要的。你的代码有点不透明。

I'm not exactly sure this will do what you want. Your code is a little opaque.

这篇关于R - 如何将循环转换为R中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆