我有一个由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: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
复制相似问题