繁体   English   中英

从不同的data.table向data.table的列分配值的最“ data.table”方法是什么

[英]What is the most “data.table” way to assign values to a column of a data.table from a different data.table

我试图将data.table b中“ True_value”列中的值分配给data.table a中相同名称的列中。 我终于得到了一些可以工作的东西,但是我不确定1)为什么有效,2)是否有更好的方法。 任何见识将不胜感激。 是的,相对而言,我已经对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])

您的示例是创建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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM