首页 > 解决方案 > 将每一行的所有列连接为一个字符串,并将其写入 R 中的另一个数据帧

问题描述

我正在尝试更改数据框的多个元素,连接每一行的所有列并将它们写入 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\")"

我不知道是什么问题,如果你能帮助我,我会很高兴的。

标签: rconcatenation

解决方案


请注意,这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"

一种解决方法是使用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

推荐阅读