Error R: The wrong length for the vector must be 2

Here is the gist of what I want to do:

I have 2 data frames:
x (id unique)

id timestamp 282462839 2012-12-05 10:55:00 282462992 2012-12-05 12:08:00 282462740 2012-12-05 12:13:00 282462999 2012-12-05 12:48:00 

y (id is not unique)

 id value1 value2 282462839 300 100 282462839 300 200 282462839 400 300 282462999 500 400 282462999 300 150 

I also have a function myfunc (id, pvalue) that calculates something and returns one of the values โ€‹โ€‹of value2 depending on the pvalue and the other value1s (more complicated than just pvalue == value1)

I want to create a third column for x that contains the corresponding computed myfunc (id, pvalue), where pvalue is an integer that is constant (say 20).

essentially I want to do this:

 x$t20 <- myfunc(x$id,20) 

I tried using lappy and sapply this way:

 x$t20 <- sapply(as.vector(x$id),myfunc,pvalue=20) 

I tried using lapply and without as.vector, but I kept getting this error:

 Error in .pointsToMatrix(p2) : Wrong length for a vector, should be 2 

This works when I just let you know where it just replicates $ id to $ t20.

How to do it?

EDIT 1: Here is the skeleton of myfunc:

 myfunc <- function(xid,pvalue) { result <- subset(y,id==xid) retVal <- -1 if(nrow(result) < 12){ return(NaN) } for(i in (1:nrow(result))){ #code to process result } return(retVal) } 
0
source share
1 answer

It was very difficult to help without complete code, but here are some tips. First you can get the logical vector id that needs to be processed, and then use the vectorized ifelse statment.

 tmp <- table(y$id) >= 12 y$t20 <- ifelse(tmp[as.character(y$id)], your_new_func(), NaN) 
+1
source

Source: https://habr.com/ru/post/1259605/


All Articles