【问题标题】:Concisely renaming/ replacing subsets of a key in data.table简明扼要地重命名/替换 data.table 中键的子集
【发布时间】:2014-08-21 15:39:18
【问题描述】:

我有一个生物数据集,其中“物种”是 data.table 的键,但有些物种名称是错误的/实际上指的是同一个物种,因此需要分组和重命名。

作为一个更小、更简单的示例,下面我使用字母表中的字母,我想将它们分组并相应地重命名为元音、辅音或两者兼有 (y)。

我可以实现目标,但我的具体问题是:有没有办法引用i中的多组密钥,然后使用:=对密钥进行分组+重命名?即,我想一步完成重命名,而不是 3。

test <- data.table(type=letters, letnum=seq_along(letters), key="type") # starting data.table
print(test) # print starting data.table

test[c("a","e","i","o","u"),type:="vowel"] # replace vowels
setkey(test, type) # need to reset key (I can't figure out to do it in the previous line)

test[c("y"), type:="both"] # replace the special case, y
setkey(test, type)

test[!c("vowel","both"), type:="consonant"] # repalce the consonants
setkey(test, type)

print(test) # print the final data.table

【问题讨论】:

    标签: r data.table subset


    【解决方案1】:

    制作你想要的更改的字典,然后你可以一步完成:

    dict = data.table(old.type = letters, new.type = "consonant", key = 'old.type')
    dict[c("a","e","i","o","u"), new.type := "vowel"]['y', new.type := 'both']
    
    setkey(test, type)
    
    test[dict, type := new.type]
    

    另一种选择是创建一个新列而不是覆盖然后每次都必须重置键。

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2015-01-19
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2012-10-30
      相关资源
      最近更新 更多