【问题标题】:An error about vectorization in R关于 R 中矢量化的错误
【发布时间】:2016-08-13 03:37:36
【问题描述】:

我的 R 代码如下。主要任务是计算重复的行数。

library(plyr)
data<-data.frame(1,2,3);
x <- read.table(text = "ID1    ID2    n    m
13    156   12   15
94    187   14   16
66    297   41   48
29    89    42   49
78    79    51   79", header= TRUE)

distfunc <- function(data,ID1,ID2,n,m){
X1<-ID1; ################
X2<-ID2; ################
X3<-unlist(mapply(':', n, m));
data<-rbind(data,data.frame(X1,X2,X3));
return(data);
}

data<-distfunc(data,x$ID1, x$ID2,x$n, x$m)

data<-data[-1,]

    plyr::count(data, names(data)); ## Calculates the row number of repetitions

我得到的错误信息:

Error in data.frame(X1, X2, X3) : 
  arguments imply differing number of rows: 5, 52

我尝试通过R Error: “In numerical expression has 19 elements: only the first used”修复它,但它失败了,结果是错误的。这个问题和那个问题不一样。

【问题讨论】:

  • 您可以使用debug(distfunc) 探索它。阅读debug() 的文档,了解如何处理调试器。
  • 您正在使用nm 的向量调用distfunc,但希望它们在该函数中作为数值工作。根据您要执行的操作,多次调用 distfunc 可能是正确的答案。

标签: r vectorization


【解决方案1】:

我刚刚修好了。

distfunc <- function(data, ID1, ID2, n, m) {
  X1 <- ID1
  X2 <- ID2
  X3 <- unlist(mapply(':', n, m))
  data <- rbind(data,data.frame(X1, X2, X3))
  return(data)
}

【讨论】:

  • data.frame(X1=10, X2=20, X3=unlist(mapply(':', x$n, x$m))) 是另一种构造数据框的方法。或data.frame(X1=10, X2=20, X3=unlist(apply(x[-1], 1, function(x) x[1]:x[2])))
  • @jogo 我更新了我的问题。它还返回错误消息。
  • 你的答案是否给出了编辑问题的预期结果?
【解决方案2】:

我想你想这样做:

# library(plyr)
# data<-data.frame(1,2,3);
x <- read.table(header=TRUE, text = 
"ID1    ID2    n    m
  13    156   12   15
  94    187   14   16
  66    297   41   48
  29    89    42   49
  78    79    51   79")

#distfunc <- function(data, ID1, ID2, n, m) {
#  X1 <- ID1 ################
#  X2 <- ID2 ################
#  X3 <- unlist(mapply(':', n, m))
#  data <- rbind(data, data.frame(X1,X2,X3))
#}

#data <- distfunc(data, x$ID1, x$ID2, x$n, x$m)
L <- apply(x, 1, function(x) data.frame(X1=x[1], X2=x[2], X3=x[3]:x[4], row.names=NULL))
data <- L[[1]]
for (i in 2:length(L)) data <- rbind(data, L[[i]])

或者在apply()中具有更好的可读性功能:

L <- apply(x, 1, function(r) data.frame(X1=r["ID1"], X2=r["ID2"], X3=r["n"]:r["m"], row.names=NULL))
data <- L[[1]]; for (i in 2:length(L)) data <- rbind(data, L[[i]])

这是一个更简单的变体:

data <- data.frame(X1=x$ID1[1], X2=x$ID2[1], X3=x$n[1]:x$m[1])
for (i in 2:nrow(x)) data <- rbind(data, data.frame(X1=x$ID1[i], X2=x$ID2[i], X3=x$n[i]:x$m[i]))

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 2016-05-30
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多