我有一个由300x300元素组成的数据框架。它们中的每一个都是-1或+1:
[,1] [,2] [,3]
[1,] 1 -1 -1
[2,] 1 1 1
[3,] -1 -1 1
[4,] 1 1 -1我想要的是迭代我的数据框架,并将每个值与每个相邻的值相乘。
即:
对于原始数据框架中的元素1,1,我需要1,1,1,2和2,1的乘积
对于原始数据框架中的元素2,2,我需要2, 2 , 1,2,2,2,3和3,2的乘积。
我尝试创建了4个新的数据框架,每个元素分别向右、左、上和下移动了1个元素:
x_up <- shift(x, 1, dir='up')
x_up <- as.array(x_up)
dim(x_up) <- dims
x_down <- shift(x, 1, dir='down')
x_down <- as.array(x_down)
dim(x_down) <- dims
x_left <- shift(x, 1, dir='left')
x_left <- as.array(x_left)
dim(x_left) <- dims
x_right <- shift(x, 1, dir='right')
x_right <- as.array(x_right)
dim(x_right) <- dims其中x是我的原始数据框架。
我可以看到,当我使用这种方法时,新的数据帧并不是正确的移位;更多的数据帧是相同的。我用相同的()检查了这个。
有别的办法解决我的问题吗?
编辑:
shift()是“binhf”库的
发布于 2015-05-17 16:04:01
我认为可能有一种更明智的方法来做到这一点,但标准的方法是迭代每个元素并乘以其周围环境。
首先:
mat <- matrix(c(1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1), ncol=3)为了避免在正边距上出现问题,您必须添加一列和一行1作为边距(例如,如果您正在求和,则肯定1在乘时不会是一个问题,必须是0's )。
mat2 <- addmargins(mat, FUN=function(x) 1)现在创建一个空矩阵来保存输出,然后对元素进行迭代并乘以邻居。
out <- matrix(nrow=nrow(mat), ncol=ncol(mat))
for (i in 1:nrow(mat)) {
for (j in 1:ncol(mat)) {
out[i,j] <- prod(mat[i,j], mat2[i-1, j], mat2[i, j-1], mat2[i+1, j], mat2[i, j+1])
}
}其结果是:
> out
[,1] [,2] [,3]
[1,] -1 1 1
[2,] -1 1 -1
[3,] 1 1 1
[4,] -1 1 -1对于300x300矩阵来说,这只花了不到1秒的时间,所以这对你来说可能已经足够了。
发布于 2015-05-17 16:29:08
这应该能起作用:
ind <- which(x==x, arr.ind=TRUE) # index matrix
# find distances (need distances of 1 or 0)
dist.mat <- as.matrix(dist(ind))
inds2mult <- apply(dist.mat, 1, function(ii) which(ii <= 1))
# get product of each list element in inds2mult
# and reform into appropriate matrix
matrix(
sapply(inds2mult, function(ii) prod(unlist(x)[ii])),
ncol=ncol(x))
# [,1] [,2] [,3]
#[1,] -1 1 1
#[2,] -1 1 -1
#[3,] 1 1 1
#[4,] -1 1 -1为了解决调用dist中的大型矩阵的内存问题,您可以尝试fields包中的fields.rdist.near函数(增量值为1):
x <- matrix(rep(-1, 300*300), ncol=300)
ind <- which(x==x, arr.ind=TRUE) # index matrix
library(fields)
ind.list <- fields.rdist.near(ind, delta=1) # took my computer ~ 15 - 20 seconds
inds2mult <- tapply(ind.list$ind[,2], ind.list$ind[,1], list)
matrix(
sapply(inds2mult, function(ii) prod(unlist(x)[ii])),
ncol=ncol(x))fields.rdist.near帮助页面中的增量参数:
阈值距离所有在距离上被三角形以上分隔的点对都被忽略了。
https://stackoverflow.com/questions/30288556
复制相似问题