包 "plyr" 的 R 函数“tapply”、"do.call" 和 "laply" 出错

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

我想将我的函数"F.w"应用到[=25的相应元素=]"t"。我尝试使用 sapplytapplydo.calllaply ...每次我遇到错误!我做错了什么?

R代码:

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)

使用 do.call 我得到了这个错误:

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

预期结果

>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

F.w函数可以改成

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