Reputation: 1
This problem bothered me the whole weekend. I want to count the number of '1's in a column based the group of another column. I want to loop through many columns, and the example I am giving here is just a simple case. I think DT1 and DT2 should give me the same result, but obviously DT1 doesn't work. Can anyone tell me what is the reason for this? Thank you!
DT <- data.table(Sample.name = c("A","B","C","A","A","B"),
Class1 = c(1, 0, 1, 0, 1, 0),
Class2 = c(1, 1, 1, 0, 1, 1))
round.test <- colnames(DT)
round.test <- round.test[c(2, 3)]
round.test <- noquote(round.test)
DT1 <- DT[, sum((round.test[1]) == 1),
by = Sample.name]
DT2 <- DT[, sum(Class1 == 1),
by = Sample.name]
Upvotes: 0
Views: 1340
Reputation: 215137
Starting with a character vector of column names, you can use get
to have the column value:
round.test <- colnames(DT)
round.test <- round.test[c(2, 3)]
DT[, sum(get(round.test[1]) == 1), .(Sample.name)]
# Sample.name V1
#1: A 2
#2: B 0
#3: C 1
DT[, lapply(round.test, function(col) sum(get(col) == 1)), .(Sample.name)]
# Sample.name V1 V2
#1: A 2 2
#2: B 0 2
#3: C 1 1
Or you can use .SDcols
to pass in the column names, and access the columns via .SD
:
DT[, lapply(.SD, function(col) sum(col == 1)), by=.(Sample.name), .SDcols=round.test]
# Sample.name Class1 Class2
#1: A 2 2
#2: B 0 2
#3: C 1 1
Upvotes: 1