[英]What is the most “data.table” way to assign values to a column of a data.table from a different data.table
I was trying to assign the values from column "True_value" in data.table b into the column of the same name in data.table a. 我试图将data.table b中“ True_value”列中的值分配给data.table a中相同名称的列中。 I finally did get something to work, but I'm not sure 1)why it worked and 2)whether there's a better way. 我终于得到了一些可以工作的东西,但是我不确定1)为什么有效,2)是否有更好的方法。 Any insight would be appreciated. 任何见识将不胜感激。 And yes, with respect, I have read up on data.table a little. 是的,相对而言,我已经对data.table有所了解。
require(data.table)
a=as.matrix(c("a","b","c"))
a=cbind(a,c("yes", "no", "maybe"))
a=cbind(a,c("NA","NA","NA"))
rownames(a)=c("one", "two","three")
colnames(a)=c("letter", "status", "True_value")
a=as.data.table(a)
b=as.data.table(c(3,13,42))
colnames(b)=c("True_value")
a[,True_value]
b[,True_value]
##this doesn't work
a[,True_value] = b[,True_value]
##this doesn't assign the values, but rather assigns the string, "True_value"
a[,"True_value"] = b[,"True_value"]
##this doesn't work
a[,.(True_value)] = b[,.(True_value)]
##none of these work
a[,.(True_value)] = unlist(b[,True_value])
a[,True_value] = unlist(b[,True_value])
##and yet this one works. Why does this work, and is there a better way to do this?
a[,"True_value"] = unlist(b[,True_value])
Your example is a really amazing way of creating a data.table :) 您的示例是创建data.table的一种非常令人惊奇的方法:)
require(data.table)
a <- data.table(letter = c("a","b","c"),
status = c("yes", "no", "maybe"),
True_value = NA_real_)
b <- data.table(True_value = c(3, 13, 42))
# I am not sure if this is the most "data.table" way of doing this,
# but it is readable at least:
a[, True_value := b[, True_value]]
require(data.table)
require(dplyr)
a <- data.table(V1 = c("a","b","c"),
V2 = c("yes", "no", "maybe"),
V3 = NA,
V4 = NA)
b <- data.table(V4 = c(1, 2, 3),
ignore = c(99),
V3 = c(3, 13, 42))
# Get positions of matching columns in a,
# thanks to match can be in any order
fromA <- match(names(b), names(a)) %>% na.omit()
# Get positions of matching columns in b in the original order
fromB <- which(names(b) %in% names(a))
a[, fromA, with = FALSE]
b[, fromB, with = FALSE]
a[, fromA :=
b[, fromB, with = FALSE],
with = FALSE]
print(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.