简体   繁体   English

使用purrr :: map将新列分配给data.tables列表

[英]using purrr::map to assign a new column to a list of data.tables

I am trying to add a new column to all data.tables residing in a list. 我试图将新列添加到列表中驻留的所有data.tables中。 All data.tables in the list have identical structure. 列表中的所有data.tables具有相同的结构。

A reprex: Let's take a simple list of 2 datatables ldt 一个代表:让我们简单列出2个数据表ldt

library(data.table)
dt1 <- data.table(x=1:3,y=(1:3)^2)
dt2 <- data.table(x=5:7,y=(1:3)^2)
ldt <- list(d1=dt1,d2=dt2)

Now suppose I want to add a new column z in both the datatables with values stored in a character vector: 现在假设我想在两个数据表中添加一个新列z ,其值存储在字符向量中:

new_col <- c("DOC1","DOC2")

So I want to attach DOC1 to dt1$z and DOC2 to dt2$z 所以我想将DOC1附加到dt1$z ,将DOC2dt2$z

I tried the following syntax of purrr::map 我尝试了以下purrr::map语法

purrr::map2(.x = ldt,.y = doc,.f = ~ ldt$z = doc)

But it gives the following error: 但是它给出了以下错误:

Error: unexpected '=' in "map2(.x = ldt,.y = doc,.f = ~ ldt$z =" 错误:“ map2(.x = ldt,.y = doc,.f =〜ldt $ z =“

I tried : 我试过了 :

 map2(.x = ldt,.y = doc,.f = function(x,y) x$z <- y)

But this results in a list output with just this: 但这会导致列表输出如下:

$d1
[1] "DOC1"

$d2
[1] "DOC2"

What am I doing wrong? 我究竟做错了什么?

Also if someone may please direct me to a purrr tutorial that takes up some different examples than the straighforward ones found here, it would be great. 另外,如果有人可以指导我进入purrr教程,该教程采用了一些与此处找到的示例不同的示例,那就太好了。

https://stackoverflow.com/a/48144294/1972786 https://purrr.tidyverse.org/reference/map2.html#arguments https://stackoverflow.com/a/48144294/1972786 https://purrr.tidyverse.org/reference/map2.html#arguments

You need to use kinda unqouting. 您需要使用unqouting。 (Sorry, I'm not familiar with data.table at all, but in tidy evaluation this term sounds like this). (对不起,我一点都不熟悉data.table ,但是在整洁的评估中,这个词听起来像这样)。 But that's how you can solve it: 但这是解决问题的方法:

What we have... 我们有什么...

library(data.table)
library(tidyverse)

dt1 <- data.table(x=1:3,y=1:3^2)
dt2 <- data.table(x=5:7,y=1:3^2)
ldt <- list(d1=dt1,d2=dt2)

new_col <- c("DOC1","DOC2")

Now you iterate over list of data.tables ( .x ) and values for new variable z ( .y ). 现在,您遍历data.tables( .x )和新变量z.y )的值的列表。 data.table use non-standard evaluation inside [] , so to create new variable named with character vector "z" you have to use := . data.table[]内使用非标准评估,因此要创建以字符向量"z"命名的新变量,您必须使用:= See the code: 看代码:

map2(ldt, new_col, ~ .x[, "z" := .y])
#> $d1
#>    x y    z
#> 1: 1 1 DOC1
#> 2: 2 2 DOC1
#> 3: 3 3 DOC1
#> 4: 1 4 DOC1
#> 5: 2 5 DOC1
#> 6: 3 6 DOC1
#> 7: 1 7 DOC1
#> 8: 2 8 DOC1
#> 9: 3 9 DOC1
#> 
#> $d2
#>    x y    z
#> 1: 5 1 DOC2
#> 2: 6 2 DOC2
#> 3: 7 3 DOC2
#> 4: 5 4 DOC2
#> 5: 6 5 DOC2
#> 6: 7 6 DOC2
#> 7: 5 7 DOC2
#> 8: 6 8 DOC2
#> 9: 7 9 DOC2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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