我有一个名为 (b2) 的矩阵,它包含 3565 行和 125 列,只有二分值(0 和 1)
我设计了一个函数来比较行i
和行i+1
并将差异的数量存储在新向量中。
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 变量
我想使用 ddply {plyr} 应用我的函数,但要做到这一点,我只需要对没有 ID 变量 ( as.matrix(b2[,1:(ncol(b2)-1)])
) 的原始矩阵进行子集化,但它一直说我的函数不是函数:(
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.
谁能帮我克服这个问题?