r - 将每一行的所有列连接为一个字符串,并将其写入 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\")"
我不知道是什么问题,如果你能帮助我,我会很高兴的。
解决方案
请注意,这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
推荐阅读
- python - 使用 groupby 时不显示 Pandas 列
- conv-neural-network - CNN 中的最小和平均池化
- impala - [ImpalaJDBCDriver](500312) 获取数据行时出错:null
- python - 如何在 Google colab 中更改 pytorch 版本
- python - “mat1 和 mat2 形状不能相乘(448x7 和 576x10)”,同时尝试执行 Layer Wise 相关传播
- c++ - 创建一个程序,该程序具有 3 个不同的变量,其数据类型为整数
- ruby - rvm install 2.6.7 在 Apple M1 mac 上总是失败
- google-bigquery - SQL中的数组排名和分组依据
- reactjs - 过渡到 React.lazy 加载的组件时闪烁
- vue.js - 有没有办法拦截vue中的一个事件,以后再继续呢?