【问题标题】:Replacing data.table observations; vector approach替换 data.table 观察;向量法
【发布时间】:2013-05-04 10:00:37
【问题描述】:

我想用一组新值替换 data.table 变量中的选择值。

### Vector of old values I would like to replace
char <- c('one', 'two', 'three', 'four', 'five', 'six', 'seven')
### Vector of new values I would like to replace old values with
num  <- as.character(1:7)

### Create a data.table
dt <- data.table(a = c(rep(char, each = 2), c('Something', 'Else', ' ', '')),
                 b = 1:18,
                 c = letters[1:18])

### Note the warning, but also that it appears to work as expected
dt[a == char, a := num]

我收到以下错误:

Warning messages:
1: In a == char :
  longer object length is not a multiple of shorter object length
2: In `[.data.table` (dt, a == char, `:=` (a, num)) :
  Supplied 7 items to be assigned to 2 items of column 'a' (5 unused)

我很好奇,这样做的正确方法是什么?

感谢您的帮助。我确实意识到我可以用蛮力达到同样的结果:

data[var == 'Seven', var := '7']
data[var == 'Six',   var := '6']
...

但是,这会在代码中引入冗余,而冗余会导致错误...

【问题讨论】:

  • 您是否希望可靠地将“one”替换为“1”,将“two”替换为“2”等?请注意,在您的示例中匹配是偶然发生的,因为 data.table 列和替换数据的长度和顺序已经匹配。
  • 您可能希望将要匹配的列 (a) 设置为 key 到您的 data.table
  • 谢谢,我已经编辑了我的玩具示例,使其更加真实。玩具示例现在抛出了我所期望的错误。

标签: r functional-programming data.table


【解决方案1】:

使用data.table 加入:

replacement = data.table(a = char, new_a = num, key = "a")

dt.fixed = replacement[dt][, a := ifelse(is.na(new_a), a, new_a)][, new_a := NULL]

【讨论】:

  • fixed &lt;- setnames(replacement[dt][is.na(new_a), new_a := a][,a := NULL],'new_a','a') 将意味着少创建一个向量(避免调用ifelse)。
  • 可能要添加的一条评论是,此方法要求 'dt' 也键入 'a',以便 data.table 连接按预期运行。感谢您的帮助!
  • 啊,谢谢 Eddi 的澄清!当我第一次尝试这种方法时,我意识到我想要修改的变量在加入后采用了“dt”第一列的值。了解这一点很有用!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 2020-09-13
  • 2019-07-15
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
相关资源
最近更新 更多