ddply {plyr}无法识别自定义函数,它告诉我我的函数不是一个函数 [英] Custom Function not recognized by ddply {plyr}, it tells me that my function is not a function

查看:110
本文介绍了ddply {plyr}无法识别自定义函数,它告诉我我的函数不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为(b2)的矩阵,其中包含3565行和125列,并且只有二分值(0和1)

I have a matrix called (b2) that contains 3565 rows and 125 columns with only dichotomous values (0 and 1)

我设计了一个函数来比较行i和行i+1,并将差异数量存储在新向量中.

I designed a function to compare row i and row i+1 and store the number of differences in a new vector.

loopPhudcf <- function(x){
  ## create a vector to store the results of your for loop
  output <- as.vector(rep(0, length(x[,1])))
  for (i in 1:(nrow(x))-1)  {
    output[i]<-as.vector(table(x[i,]==x[i+1,]))[1]
  }
  a<-nrow(x)
  b<-nrow(x)-1
  output<-t(as.matrix(output[c(a,1:b)]))
  output[output==ncol(x)]<-0
  return(output)
}

phudcfily123<-loopPhudcf(b2)

该函数运行良好,但是我还有一个ID变量,该变量使用以下命令添加到我的原始矩阵中:b2<-transform(b2,id=a$id),然后导致3565 x 126是最后一个id变量

The function works fine, but I also have an ID variable which I added to my original matrix using: b2<-transform(b2,id=a$id), then resulting in a 3565 by 126 being the last one the id variable

我想使用ddply {plyr}应用我的函数,但是要做到这一点,我只需要对我的原始矩阵进行子集操作,而不需要ID变量(as.matrix(b2[,1:(ncol(b2)-1)])),但是我一直在说我的函数不是一个函数:(

I wanted to apply my function using ddply {plyr} but to do this i need to subset only my original matrix without the ID variable (as.matrix(b2[,1:(ncol(b2)-1)])) but it keeps saying that my function is not a function :(

x <- ddply(.data = b2, .var = c("id"), .fun = loopPhudcf(as.matrix(b2[,1:(ncol(b2)-1)])))

Error in llply(.data = .data, .fun = .fun, ..., .progress = .progress,  : 
  .fun is not a function.

有人可以帮助我克服这个问题吗?

can anyone help me overcome this issue?

推荐答案

谢谢, 使用包reshape,我能够使用Brian的方法获得相同的结果,这是代码:

Thank you, using the package reshape i was able to get the same result reached using Brian's method, this is the code:

x<-sparseby(as.matrix(b2[,1:125]),list(group = b2[,126]), function(subset) loopPhudcf(as.matrix(b2[,1:125])))

令我有些奇怪的是,使用这种方法以及Brian I提出的方法,我获得了一个新的矩阵,而不是我想要的矢量

Something a little bit strange to me was that using this approach and the approach kindly suggested by Brian I obtained a new matrix instead of my desired vector

dim(x)
[1]  155 3566

因此,由于行包含相同的信息,因此我仅需对第一行进行子集即可获得向量.我的向量的长度为3565,是使用以下方法获得的:

So, I only had to subset the first row to get the vector since the rows contained the same information. My vector with a length of 3565 was obtained using:

x1<-x[1,2:ncol(x)]

我从2开始,因为第一列说明b2中的id变量. 再次谢谢你!

I started with 2 given that The first column accounts for the id variable in b2. Thank you again!

这篇关于ddply {plyr}无法识别自定义函数,它告诉我我的函数不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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