1

コンマ区切りの数字を持つ 22.388 行を含む .csv ファイルがあります。各行の数値のペアのすべての可能な組み合わせを個別に見つけて、それらをペアごとにリストして、それらをクラスターとして視覚的に表現できるようにしたいと考えています。

私のファイルの 2 つの行の例は、
「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")

これにより、入力が値のリストに読み込まれます。

input.lines  <- readLines(csv)
input.values <- strsplit(input.lines, ',')

これにより、ペアのネストされたリストが作成されます。

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

しかし、.csv ファイルの各行を個別に実行する関数が必要なので、関数で for ループを実行する必要があると思います。

前もって感謝します。

4

1 に答える 1

0

あなたが何を求めているのか正確にはわかりませんが、おそらく次のようなものです:

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
于 2013-05-09T14:18:48.987 に答える