データフレームの複数の要素を変更し、各行のすべての列を連結して、Rの新しいデータフレームに書き込もうとしています。辞書を使用して複数の要素を変更するには、ここでRamnathのソリューションに従いました。
以下に私のサンプルコードを示します。
arr <- c(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1073741824)
dict = list('1' = 'germline', '2' = 'somatic', '4' = 'inherited', '8' = 'paternal',
'16' = 'maternal', '32' = 'de-novo', '64' = 'biparental', '128' = 'uniparental',
'256' = 'not-tested', '512' = 'tested-inconclusive', '1024' = 'not-reported',
'1073741824' = 'other')
a <- data.frame(t(combn(arr, 3)), stringsAsFactors = FALSE)
nr = nrow(a)
b <- as.data.frame(matrix(nrow = nr, ncol = 1))
row.names(b) <- rowSums(a)
a[] <- lapply(a, as.character)
for (j in 1:length(dict)) {
a <- replace(a, a == names(dict[j]), dict[j])
}
for (i in 1:nr) {
b[i, 1] <- paste(as.character(as.vector(a[i,])), collapse = ", ")
}
私の期待される出力は(例)です:
> b[1,1]
[1] germline, somatic, inherited
しかし、私はこれを取得します:
> b[1,1]
[1] "list(\"germline\"), list(\"somatic\"), list(\"inherited\")"
何が問題なのかわからなかったので、手伝っていただければ幸いです。
それa[i,]
は、data.frame
たとえばから見ることができることに注意してください
> str(a[1,])
'data.frame': 1 obs. of 3 variables:
$ X1:List of 1
..$ : chr "germline"
$ X2:List of 1
..$ : chr "somatic"
$ X3:List of 1
..$ : chr "inherited"
1つの回避策は使用しています unlist(a[i,])
for (i in 1:nr) {
b[i, 1] <- paste(unlist(a[i, ]), collapse = ", ")
}
そのような
> head(b)
V1
7 germline, somatic, inherited
11 germline, somatic, paternal
19 germline, somatic, maternal
35 germline, somatic, de-novo
67 germline, somatic, biparental
131 germline, somatic, uniparental
より簡単なオプションはdo.call
+を使用することですpaste
b[, 1] <- do.call(paste, c(a, sep = ", "))
これは
> head(b)
V1
7 germline, somatic, inherited
11 germline, somatic, paternal
19 germline, somatic, maternal
35 germline, somatic, de-novo
67 germline, somatic, biparental
131 germline, somatic, uniparental
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加