r - Looping a function for each row in csv -
i have .csv file containing 22.388 rows comma seperated numbers. want find possible combinations of pairs of numbers each row seperately , list them pair pair, i'll able make visual representation of them clusters.
an example of 2 rows file
"2, 13"
"2, 8, 6"
when use str() function r says file contains factors. guess needs integers, need rows seperate, therefore i've wrapped each row in " ".
i want possible combinations of pairs each row this.
2, 13
2, 8
2, 6
8, 6
i've gotten answer @flodel saying
sample input - replace textconnection(...) csv filename.
csv <- textconnection("2,13 2,8,6")
this reads input list of values:
input.lines <- readlines(csv) input.values <- strsplit(input.lines, ',')
this creates nested list of pairs:
pairs <- lapply(input.values, combn, 2, simplify = false) puts in nice matrix of integers: pairs.mat <- matrix(as.integer(unlist(pairs)), ncol = 2, byrow = true) pairs.mat
but need function run through each row in .csv file seperately, think need loop function - can't head around it.
thanks in advance.
not sure you're after maybe this:
dat <- readlines(n=2) #read in data 2, 13 2, 8, 6 ## split each string on "," , remove white space ## , put list lapply dat2 <- lapply(dat, function(x) { as.numeric(gsub("\\s+", "", unlist(strsplit(x, ",")))) }) ## find combinations using outer outer (faster ## expand.grid , can take triangle) dat3 <- lapply(dat2, function(x) { y <- outer(x, x, paste) c(y[upper.tri(y)]) }) ## split on spaces , convert numeric ## stored list lapply(strsplit(unlist(dat3), " "), as.numeric) ## > lapply(strsplit(unlist(dat3), " "), as.numeric) ## [[1]] ## [1] 2 13 ## ## [[2]] ## [1] 2 8 ## ## [[3]] ## [1] 2 6 ## ## [[4]] ## [1] 8 6
Comments
Post a Comment