Rotate vector output into columns in data.table along with other columns?

My questions are related to this:

Rotate vector output into columns in data.table?

But my situation is a little more complicated. I not only return the vector as columns, but also compute other columns at the same time. For instance:.

DT = data.table(X = 1:10, Y = 11:20, Z = 21:30, group = rep(1:10, each = 3)) featuresDT <- quote(list(x = mean(X), y = mean(Y), z = mean(Z), as.list(quantile(X)))) DT[, eval(featuresDT), by = "group"] 

where quantile returns a vector of length 5. Instead of getting a data table with 8 columns, I get one of 4 columns, and the quantile results quantile displayed as additional rows, and x, y and z duplicated 5 times. I also tried dist = as.list(quantile(X) , but this gives the same result but a different column name.

+4
source share
2 answers

You should just change list to c . c with any value of type list will automatically result in list ):

 featuresDT <- quote(c(x = mean(X), y = mean(Y), z = mean(Z), as.list(quantile(X)))) DT[, eval(featuresDT), by = "group"] group xyz 0% 25% 50% 75% 100% 1: 1 2.000000 12.00000 22.00000 1 1.5 2 2.5 3 2: 2 5.000000 15.00000 25.00000 4 4.5 5 5.5 6 3: 3 8.000000 18.00000 28.00000 7 7.5 8 8.5 9 4: 4 4.333333 14.33333 24.33333 1 1.5 2 6.0 10 5: 5 4.000000 14.00000 24.00000 3 3.5 4 4.5 5 6: 6 7.000000 17.00000 27.00000 6 6.5 7 7.5 8 7: 7 6.666667 16.66667 26.66667 1 5.0 9 9.5 10 8: 8 3.000000 13.00000 23.00000 2 2.5 3 3.5 4 9: 9 6.000000 16.00000 26.00000 5 5.5 6 6.5 7 10: 10 9.000000 19.00000 29.00000 8 8.5 9 9.5 10 
+3
source

Try the following:

 featuresDT <- quote(cbind(list(x = mean(X), y = mean(Y), z = mean(Z)), as.data.table(t(quantile(X))))) 
+1
source

Source: https://habr.com/ru/post/1496551/


All Articles