data-manipulation
Postgres: convert single row to multiple rows (unpivot)
A single SELECT with a LATERAL join to a VALUES expression does the job of “un-pivoting” columns to separate rows: SELECT p.id, v.* FROM price_list p CROSS JOIN LATERAL ( VALUES (‘type_a’, p.price_type_a) , (‘type_b’, p.price_type_b) , (‘type_c’, p.price_type_c) ) v (price_type, price); Related: Convert one row into multiple rows with fewer columns SELECT DISTINCT … Read more
Arranging rows in custom order using dplyr
We can use factor to change the order in a custom way df %>% arrange(factor(Reg, levels = LETTERS[c(3, 1, 2)]), desc(Res), desc(Pop)) # Reg Res Pop #1 C Urban 501638 #2 C Rural 499274 #3 A Urban 500414 #4 A Rural 500501 #5 B Urban 499922 #6 B Rural 500016 Or with match to get … Read more
R: x ‘probs’ outside [0,1]
The x values generated are random and they can be positive or negative. probs argument of quantile needs to have values between 0 and 1. One way would be to take the absolute value of x[5:7] and turn them to ratio using prop.table. x[5:7] <- prop.table(abs(x[5:7])) Complete function – library(optimization) fitness <- function(x) { #bin … Read more
Assign value to group based on condition in column
Here’s a quick data.table one library(data.table) setDT(df)[, newValue := date[value == 4L], by = group] df # group date value newValue # 1: 1 1 3 2 # 2: 1 2 4 2 # 3: 1 3 3 2 # 4: 2 4 4 4 # 5: 2 5 5 4 # 6: 2 6 … Read more
Removing elements with Array.map in JavaScript
You should use the filter method rather than map unless you want to mutate the items in the array, in addition to filtering. eg. var filteredItems = items.filter(function(item) { return …some condition…; }); [Edit: Of course you could always do sourceArray.filter(…).map(…) to both filter and mutate]
R: Obtaining Rules from a Function
This isn’t my area of expertise, but perhaps this function (from https://www.togaware.com/datamining/survivor/Convert_Tree.html) will do what you want to do: library(rpart) car.test.frame$Reliability = as.factor(car.test.frame$Reliability) z.auto <- rpart(Reliability ~ ., car.test.frame) plot(z.auto, margin = 0.25) text(z.auto, pretty = TRUE, cex = 0.8, splits = TRUE, use.n = TRUE, all = FALSE) list.rules.rpart <- function(model) { if (!inherits(model, … Read more