R数据表,访问赋值函数内的矩阵 [英] R data.table, accessing a matrix inside an assignment function
问题描述
我有以下data.table
结构(list(xi = c(1,1,1,2 ,2,2,3,3,3),yi = c(1,2,
3,1,2,3,1,2,3),flag = c(0,0,0,0) ,0,0,0,0,0)),.names = c(xi,
yi,flag),row.names = c(NA,-9L),class = c (data.table,
data.frame),.internal.selfref =< pointer:0x11a1a78>)
我也有一个 3x3
矩阵如下。
code>结构(c(1,1,0.4,1,0,0,1,0,0.2),.Dim = c(3L,3L))
/ pre>
我想为data.table
flag
指定一个第三列,由xi
行和yi
列表示的矩阵小于1,则flag = 1
else 0.我为此写了一个函数,func < ,m){
if(m [x,y] <1){
return(1)
}
else {
return(0)
}
}
但是,如果我尝试
y [,flag:= func(xi,yi,m)]
我的标志值总是0.有人可以指出我在这里做错了吗?
提前感谢。解决方案您不需要自定义函数...
dt [,flag:= as.integer(m [cbind(xi,yi)]< 1)]
你需要小心的以正确的方式索引矩阵(使用
cbind / code>而不是
[,]
形式的索引)。I've the following data.table
structure(list(xi = c(1, 1, 1, 2, 2, 2, 3, 3, 3), yi = c(1, 2, 3, 1, 2, 3, 1, 2, 3), flag = c(0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("xi", "yi", "flag"), row.names = c(NA, -9L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x11a1a78>)
I also have a
3x3
matrix as below.structure(c(1, 1, 0.4, 1, 0, 0, 1, 0, 0.2), .Dim = c(3L, 3L))
I want to assign a third column to the data.table
flag
such that if the element in the matrix represented by thexi
row andyi
column is less than 1, thenflag = 1
else 0. I wrote a function for this,func <- function (x, y, m) { if (m[x, y] < 1) { return(1) } else { return(0) } }
However, if I try
y[,flag := func(xi,yi,m)]
my flag values are always 0. Could someone point out what I'm doing wrong here? Thanks in advance.
解决方案You don't need a custom function...
dt[ , flag := as.integer( m[cbind(xi,yi)] < 1 ) ]
You do need to be careful to index the matrix in the correct way (using
cbind(...)
rather than[,]
form of indexing).这篇关于R数据表,访问赋值函数内的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!