在data.table中简要地重命名/替换键的子集

时间:2014-08-21 15:39:19

标签: r data.table subset

我有一个生物数据集,其中“物种”是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

1 个答案:

答案 0 :(得分:0)

制作所需更改的字典,然后您可以一步完成所有操作:

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]

另一种方法是创建一个新列而不是覆盖,然后每次都必须重置密钥。