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

时间:2016-04-07 22:18:13

标签: r data.table

我试图将data.table b中列“True_value”的值分配到data.table a中的同名列中。我终于确实得到了一些工作,但我不确定1)为什么它起作用2)是否有更好的方法。任何见解将不胜感激。是的,尊重,我已经阅读了data.table一点。

$g95 bsp.f03 -I/usr/local/include/g95 -L/usr/local/lib -lgsl -lfgsl_g95 -lgslcblas
-bash: g95: command not found

1 个答案:

答案 0 :(得分:4)

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