我试图将data.table b中的“data.table”列的值赋值到data.table a中同名的列中。我最终得到了一些有用的东西,但我不确定它为什么工作,以及是否有更好的方法。任何洞察力都将不胜感激。是的,恕我直言,我在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])发布于 2016-04-07 22:33:43
您的示例是创建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)https://stackoverflow.com/questions/36488199
复制相似问题