[datatable-help] R function
Douglas Clark
clark9876 at airquality.dk
Thu Nov 5 10:45:02 CET 2015
A data.table way to do this could be:
library(data.table)
x = c(10, 25, 4, 10, 9, 4, 4)
DT <- data.table(x)
DT
# x
# 1: 10
# 2: 25
# 3: 4
# 4: 10
# 5: 9
# 6: 4
# 7: 4
# create a new column y as the count in each group defined by x
DT[, y := .N, by = x]
DT
# x y
# 1: 10 2
# 2: 25 1
# 3: 4 3
# 4: 10 2
# 5: 9 1
# 6: 4 3
# you can then either directly use DT$y
DT$y
# [1] 2 1 3 2 1 3 3
# or extract the y column to a separate vector y
y <- DT[, y]
y
# [1] 2 1 3 2 1 3 3
# or all of the above in one line:
y <- data.table(x = c(10, 25, 4, 10, 9, 4, 4) )[, y := .N, by = x][, y]
y
# [1] 2 1 3 2 1 3 3
--
View this message in context: http://r.789695.n4.nabble.com/R-function-tp4714299p4714387.html
Sent from the datatable-help mailing list archive at Nabble.com.
More information about the datatable-help
mailing list