我试图更改数据框架的多个元素,将每一行的所有列连接起来,并将它们写入R中的一个新数据框架中,以便使用字典更改多个元素,我在here中遵循了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\")"我不知道是什么问题,如果你能帮我解决问题,我会很高兴的。
发布于 2021-01-18 16:45:00
请注意,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, uniparentalhttps://stackoverflow.com/questions/65778402
复制相似问题