【发布时间】:2016-05-02 14:22:15
【问题描述】:
我试图让这个函数运行得更快。理想情况下,我会在数据帧上运行类似 apply 之类的东西,让它比我目前拥有的更快地吐出结果。这个函数的作用是它需要一个看起来像这样的数据框
df
Var1 Var2
5 0
9 0
4 1
6 1
2 2
4 2
然后它遍历每一行并检查数据框中其他行的值(在 Var1 和 Var2 中)最接近您所在行中 Var1 和 Var2 的值。然后输出哪些行最接近其他行的列表。例如
myFunc(df)
[[1]]
[1] 3 4
[[2]]
integer(0)
[[3]]
[1] 1 6
[[4]]
[1] 1
[[5]]
integer(0)
[[6]]
[1] 3
因此,第 1 行的值最接近第 3 行和第 4 行,而第 2 行附近没有其他行。这是我的函数
myFunc = function(t) {
x=matrix(); x2=list()
y = matrix(); y2 = list()
for (i in 1:nrow(t)){
for (j in 1:nrow(t)){
#this will check for other rows <= 1 from the row I am currently in
if (abs(t[i,1] - t[j,1]) <= 1) {
x[j] = j
} else { x[j] = NA }
if (abs(t[i,2] - t[j,2]) <= 1) {
y[j] = j
} else { y[j] = NA }
}
x2[[i]] = x
y2[[i]] = y
}
for (i in 1:length(x2)){
x2[[i]] = x2[[i]][!x2[[i]] == i]
y2[[i]] = y2[[i]][!y2[[i]] == i]
}
x2 = lapply(x2, function(x) x[!is.na(x)])
y2 = lapply(y2, function(x) x[!is.na(x)])
#this intersects Var1 and Var2 to find factors that are close to both Var1 and Var2
z = list()
for (i in 1:length(x2)){
z[[i]] = intersect(unlist(x2[[i]]), unlist(y2[[i]]))
}
return(z)}
【问题讨论】:
-
从您的代码看来,
apply(as.matrix(dist(DF, "maximum")) == 1L, 2, which)之类的内容可能会有所帮助?