简体   繁体   中英

Row indices in data.table in R

How do I control the row indices in data.table in R?

I want to check if the value in a row matches the previous one:

patient    produkt    output
1          Meg        Initiation
1          Meg        Continue
1          Gem        Switch
2          Pol        Initiation
2          Pol        Continue
2          Pol        Continue

Where the output column is the output, I wish (could be replaced with numbers if that is easier though such that initiation=0, continue=1, switch=2 ).

I can't find out how to control the indices in data.table, and the following does not work

test[ , switcher2 := identical(produkt, produkt[-1]),by=patient]

Any ideas are welcome. It has to be in a data.table though.

Here's an attempt using the new shift function from the devel version on GH

I've used the 0:2 notation here as it is shorter to write but you can use words instead

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

I'm basically always starting with a 0 per each group and then comparing against the previous value per group. If TRUE then 1 is assigned. If FALSE then 2 is assigned.


If you want it in words, here's alternative verison

test[ ,output3 := c("Initiation", c("Switch", "Continue")[(produkt == shift(produkt)) + 1][-1]), by = patient]

Installation instructions:

library(devtools)
install_github("Rdatatable/data.table", build_vignettes = FALSE)

Here an option using diff . I am using ifelse to change integer values to characters. Finally , for each group , first element is set to an initial value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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