我想将我的功能 “F.w” 应用于 “t” 的相应元素。我尝试使用 sapply , tapply , do.call , laply ......每次我获得错误!我做错了什么?
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我收到了这个错误:
警告信息:1:在is.na(e1)|中is.na(e2):较长的物体长度 不是较短物体长度2的倍数:在
==.default
中(数据$ X1, unique(数据$ X1)[j]):较长的对象长度不是倍数 较短的物体长度3:在Data $ X2 [i]&lt; - as.numeric(unlist(w [j]))中:
要替换的项目数量不是替换长度的倍数
预期结果
>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
答案 0 :(得分:1)
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