Search code examples
rapplysapplytapplydo.call

Error with R function “tapply” , "do.call" , and "laply" of th package "plyr"


I would like to apply my function "F.w" to the corresponding element of "t". I tried to use sapply, tapply, do.call, laply... and every time I get an error ! What i am doing wrong?

R code :

Data=data.frame(X1=c("A","B","B","B","B","B","B","B","B","B","B","B","A","B",
               "C","B","B","A","A","A","B","B","C","C","A","B","A","B"),
             X2=rep(0,28))
w=list(rep(0.2,7),rep(0.5,18),rep(0.8,3))
F.w <- function(j){
  i <- which(Data$X1== unique(Data$X1)[j])
  Data$X2[i] <- as.numeric(unlist(w[j]))
  return(Data)
}
t= c(1,2,3)

library(plyr)
laply(t,F.w)

do.call(F.w,list(t),quote = TRUE)

tapply(t,t,F.w)

With do.call i got this error :

Warning messages: 1: In is.na(e1) | is.na(e2) : longer object length is not a multiple of shorter object length 2: In ==.default(Data$X1, unique(Data$X1)[j]) : longer object length is not a multiple of shorter object length 3: In Data$X2[i] <- as.numeric(unlist(w[j])) :
number of items to replace is not a multiple of replacement length

Expected result

>Data
   X1  X2
1   A 0.2
2   B 0.5
3   B 0.5
4   B 0.5
5   B 0.5
6   B 0.5
7   B 0.5
8   B 0.5
9   B 0.5
10  B 0.5
11  B 0.5
12  B 0.5
13  A 0.2
14  B 0.5
15  C 0.8
16  B 0.5
17  B 0.5
18  A 0.2
19  A 0.2
20  A 0.2
21  B 0.5
22  B 0.5
23  C 0.8
24  C 0.8
25  A 0.2
26  B 0.5
27  A 0.2
28  B 0.5

Solution

  • The F.w function can be changed to

    F.w <- function(dat, w1){
      i <- match(dat[["X1"]], unique(dat[["X1"]]))
      unlist(w1)[ rank(i, ties.method = "first")]
    }
    
    Data$X2 <-  F.w(Data, w)
    Data$X2
    #[1] 0.2 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.2 0.5 0.8 0.5 0.5
    #[18] 0.2 0.2 0.2 0.5 0.5 0.8 0.8 0.2 0.5 0.2 0.5