r - Is there a simple way of pairing unique data points in a data frame? -
i want extract pairs of data data frame, paired data not in own column. each number in column 1 paired numbers right of column. likewise numbers in column 2 paired numbers in columns 3 or above.
i have created script using bird's nest of 'for' loops feel there should more elegant way it.
example data:
structure(list(a = 1:3, b = 4:6, c = 7:9), .names = c("a", "b", "c"), class = "data.frame", row.names = c(na, -3l))
desired output:
structure(list(x1 = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6), x2 = c(4, 5, 6, 7, 8, 9, 4, 5, 6, 7, 8, 9, 4, 5, 6, 7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9)), .names = c("x1", "x2"), row.names = c(na, 27l), class = "data.frame")
here's approach using data.table
package , efficient cj
, rbindlist
functions (assuming data set called df
)
library(data.table) res <- rbindlist(lapply(seq_len(length(df) - 1), function(i) cj(df[, i], unlist(df[, -(seq_len(i))]))))
you set column names reference (if insist on "x1" , "x2") using setnames
setnames(res, 1:2, c("x1", "x2"))
you can convert data.frame
reference (if want match desired output "exactly") using setdf()
setdf(res)
Comments
Post a Comment