R中data.table中的行索引
如何控制R中data.table中的行索引 我想检查一行中的值是否与前一行中的值匹配:R中data.table中的行索引,r,data.table,R,Data.table,如何控制R中data.table中的行索引 我想检查一行中的值是否与前一行中的值匹配: patient produkt output 1 Meg Initiation 1 Meg Continue 1 Gem Switch 2 Pol Initiation 2 Pol Continue 2 Pol
patient produkt output
1 Meg Initiation
1 Meg Continue
1 Gem Switch
2 Pol Initiation
2 Pol Continue
2 Pol Continue
如果输出列是输出,我希望(如果更容易,可以用数字替换,尽管initiation=0,continue=1,switch=2
)
我无法找到如何控制data.table中的索引,下面的方法不起作用
test[ , switcher2 := identical(produkt, produkt[-1]),by=patient]
欢迎提出任何意见。但它必须位于data.table中。这里尝试使用 我在这里使用了
0:2
符号,因为它写起来比较短,但是你可以用单词来代替
test[ , output2 := c(0, (2:1)[(produkt == shift(produkt)) + 1][-1]), by = patient]
# patient produkt output output2
# 1: 1 Meg Initiation 0
# 2: 1 Meg Continue 1
# 3: 1 Gem Switch 2
# 4: 2 Pol Initiation 0
# 5: 2 Pol Continue 1
# 6: 2 Pol Continue 1
我基本上总是从每组的0
开始,然后与每组之前的值进行比较。如果TRUE
则分配1
。如果FALSE
则分配2
如果你想用文字表达,这里有另一种verison
test[ ,output3 := c("Initiation", c("Switch", "Continue")[(produkt == shift(produkt)) + 1][-1]), by = patient]
安装说明:
library(devtools)
install_github("Rdatatable/data.table", build_vignettes = FALSE)
这里有一个使用
diff
的选项。我正在使用ifelse
将整数值更改为字符。最后,对于每个组,将第一个元素设置为初始值
setDT(dx)[,output := {
xx <- ifelse(c(0,diff(as.integer(factor(produkt))))<0,
"Switch","Continue")
xx <- as.character(xx)
xx[1] <- "Initiation"
xx
},
patient]
# patient produkt output
# 1: 1 Meg Initiation
# 2: 1 Meg Continue
# 3: 1 Gem Switch
# 4: 2 Pol Initiation
# 5: 2 Pol Continue
# 6: 2 Pol Continue
setDT(dx)[,输出:={
xx也许有人知道像diff()这样的命令,但是对于factors?非常感谢你的回答。我已经更改了Switch->Continue,如果produkt变量更改为:Meg->Gem->Meg。但是除此之外:完美:)谢谢你的回复!