[英]R data.table, accessing a matrix inside an assignment function
I've the following data.table 我有以下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. 我也有一个3x3
矩阵如下。
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 the xi
row and yi
column is less than 1, then flag = 1
else 0. I wrote a function for this, 我想为data.table flag
分配第三列,这样如果xi
row和yi
列表示的矩阵中的元素小于1,则flag = 1
else 0.我为此写了一个函数,
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? 我的旗帜值总是0.有人能指出我在这里做错了吗? 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). 您需要小心以正确的方式索引矩阵(使用cbind(...)
而不是[,]
索引形式)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.