R combine data frame columns with regex -
this question has answer here:
i have following data frame:
dat <- data.frame( c = c(1 , 2) , a1 = c(1 , 2) , a2 = c(3 , 4) , b1 = c(5 , 6) , b2 = c(7 , 8) ) c a1 a2 b1 b2 1 1 1 3 5 7 2 2 2 4 6 8
that merged columns based on shared prefixes become data frame:
dat2 <- data.frame( c = c(1 , 2 , 1 , 2) , = c(1 , 2 , 3 , 4) , b = c(5 , 6 , 7 , 8) ) c b 1 1 1 5 2 2 2 6 3 1 3 7 4 2 4 8
the way can think of try using melt()
. attempt:
melt(dat , measure.vars = c(grep("^a" , colnames(dat)) , grep("^b" , colnames(dat)))) variable value 1 1 a1 1 2 2 a1 2 3 1 a2 3 4 2 a2 4 5 1 b1 5 6 2 b1 6 7 1 b2 7 8 2 b2 8 >
needless say, incorrect.
we can use melt
data.table
takes multiple patterns
in measure
library(data.table) melt(setdt(dat), measure=patterns("^a\\d+", "^b\\d+"), value.name=c("a", "b"))[, variable:= null][] # c b #1: 1 1 5 #2: 2 2 6 #3: 1 3 7 #4: 2 4 8
Comments
Post a Comment