简体   繁体   English

使用列表更改 data.table 列中的值

[英]Use list to change values in column data.table

I want to use a list as a simple dictionary to change values when the lookup to the list is not null.当对列表的查找不是 null 时,我想将列表用作简单的字典来更改值。 I'd expected this to work, but it doesn't;我希望这会起作用,但事实并非如此;

assoc_values <- list("A" = "GROUP1", "C" = "GROUP1", "B" = "GROUP2", "D" = "GROUP3")
some_data_table[!is.null(assoc_values[[lookup_column]]), "mapped_col" := assoc_values[[lookup_column]]]

It fails with error msg Error: recursive indexing failed at level 2 .它失败并出现错误 msg Error: recursive indexing failed at level 2 I've tried other approaches like ifelse(.is,null(assoc_values[[lookup_column]]). ...) but always fails.我尝试过其他方法,例如ifelse(.is,null(assoc_values[[lookup_column]]). ...)但总是失败。

below there is a reproducible example:下面有一个可重现的例子:

library(data.table)
assoc_values <- list("A" = "GROUP1", "C" = "GROUP1", "B" = "GROUP2", "D" = "GROUP2")
some_data_table <- data.table('col1' = seq(1, 10), 'lookup_column' = c('A', 'A', 'E', 'B', 'D', 'C', 'A', 'F', 'C', 'T'))
some_data_table[!is.null(assoc_values[[lookup_column]]), "mapped_col" := assoc_values[[lookup_column]]]

You don't really need a list here since a named vector would do.你真的不需要一个列表,因为命名向量就可以了。

library(data.table)
assoc_values <- c("A" = "GROUP1", "C" = "GROUP1", "B" = "GROUP2", "D" = "GROUP2")
some_data_table <- data.table(col1 = seq(1, 10), 
                              lookup_column = c('A', 'A', 'E', 'B', 'D',
                                                'C', 'A', 'F', 'C', 'T'))


some_data_table[, new_col := assoc_values[lookup_column]]
some_data_table[is.na(new_col), new_col := lookup_column]

some_data_table

#    col1 lookup_column new_col
# 1:    1             A  GROUP1
# 2:    2             A  GROUP1
# 3:    3             E       E
# 4:    4             B  GROUP2
# 5:    5             D  GROUP2
# 6:    6             C  GROUP1
# 7:    7             A  GROUP1
# 8:    8             F       F
# 9:    9             C  GROUP1
#10:   10             T       T

The error is to mistake '[' with '[[' , see this SO post .错误是误将'[''[[' ,请参阅此 SO 帖子 The solution is to use assoc_values[lookup_column] .解决方案是使用assoc_values[lookup_column]

some_data_table[!is.null(assoc_values[lookup_column]), 
                "mapped_col" := assoc_values[lookup_column]]

some_data_table
#    col1 lookup_column mapped_col
# 1:    1             A     GROUP1
# 2:    2             A     GROUP1
# 3:    3             E           
# 4:    4             B     GROUP2
# 5:    5             D     GROUP2
# 6:    6             C     GROUP1
# 7:    7             A     GROUP1
# 8:    8             F           
# 9:    9             C     GROUP1
#10:   10             T           

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

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