R 为csv中的每一行循环一个函数
我有一个.csv文件,包含22.388行,以逗号分隔的数字。我想分别为每一行找到所有可能的数字对组合,并逐个列出它们,这样我就能够将它们可视化表示为簇 我的文件中的两行示例如下R 为csv中的每一行循环一个函数,r,for-loop,R,For Loop,我有一个.csv文件,包含22.388行,以逗号分隔的数字。我想分别为每一行找到所有可能的数字对组合,并逐个列出它们,这样我就能够将它们可视化表示为簇 我的文件中的两行示例如下 “2,13” “2、8、6” 当我使用str()函数时,R表示文件包含因子。我想它需要是整数,但我需要行是分开的,因此我将每一行都包装在“”中 我希望每一行有可能的成对组合,就像这样 2,13 2,8 2,6 8,6 我已经从@flodel那里得到了答案 示例输入-将textConnection(…)替换为csv文件名
“2,13”
“2、8、6” 当我使用str()函数时,R表示文件包含因子。我想它需要是整数,但我需要行是分开的,因此我将每一行都包装在“”中 我希望每一行有可能的成对组合,就像这样 2,13
2,8
2,6
8,6
我已经从@flodel那里得到了答案 示例输入-将textConnection(…)替换为csv文件名
csv <- textConnection("2,13
2,8,6")
csv不确定你到底想要什么,但可能是这样的:
dat <- readLines(n=2) #read in your data
2, 13
2, 8, 6
## split each string on "," and then remove white space
## and put into a list with lapply
dat2 <- lapply(dat, function(x) {
as.numeric(gsub("\\s+", "", unlist(strsplit(x, ","))))
})
## find all combinations using outer with outer (faster
## than expand.grid and we can take just a triangle)
dat3 <- lapply(dat2, function(x) {
y <- outer(x, x, paste)
c(y[upper.tri(y)])
})
## then split on the spaces and convert back to numeric
## stored as a 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
dat您应该提供一个可复制的小示例。在某种程度上,他们确实提供了一个示例,当他们说时,数据是什么样子的。我的文件中的两行示例将是
,但它在当前状态下无法运行。非常感谢!这似乎是可行的,现在唯一的问题是,我需要把它放到Gephi中进行可视化,但我的R需要很长时间,而且还没有制作出我的表格。
pairs <- lapply(input.values, combn, 2, simplify = FALSE)
This puts everything in a nice matrix of integers:
pairs.mat <- matrix(as.integer(unlist(pairs)), ncol = 2, byrow = TRUE)
pairs.mat
dat <- readLines(n=2) #read in your data
2, 13
2, 8, 6
## split each string on "," and then remove white space
## and put into a list with lapply
dat2 <- lapply(dat, function(x) {
as.numeric(gsub("\\s+", "", unlist(strsplit(x, ","))))
})
## find all combinations using outer with outer (faster
## than expand.grid and we can take just a triangle)
dat3 <- lapply(dat2, function(x) {
y <- outer(x, x, paste)
c(y[upper.tri(y)])
})
## then split on the spaces and convert back to numeric
## stored as a 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