亲爱的 stackoverflow 社区,
我认为我对 R 有经验,但上周 R 证明我错了。 我认为我的问题很容易解决,但我不能,所以我向你们伸出援手!
我的一些测序数据有问题,希望它采用另一种形式的矩阵(如 OTU 表)。 这是一个非常大的数据集,因此下表只是其中的一小部分。总共有 8 个条形码,就像 14 个不同的物种。
现在处于以下矩阵/结构中:
barcode name fraction
1 barcode01 Escherichia 0.2
2 barcode01 Bacteria 0.6
3 barcode02 Escherichia 0.2
4 barcode02 Bacteria 0.3
5 barcode03 Escherichia 0.4
6 barcode03 Bacteria 0.1
我希望它具有以下结构(如OTU表):
barcode01 barcode02 barcode03
Escherichia 0.2 0.2 0.4
Bacteria 0.6 0.3 0.1
我尝试将数据写为向量:
asv <- as.vector(test)
matrix(asv, dimnames = list(asv$barcode, asv$name))
但我收到一条错误消息:
Error in matrix(asv, dimnames = list(asv$barcode, asv$name)) :
length of 'dimnames' [1] not equal to array extent
有人有答案/解决方案吗? 留意你的消息!
亲切的问候, 马尔温
我想你想要
library(tidyr)
data |>
pivot_wider(names_from = barcode, values_from = fraction)
#> # A tibble: 2 × 4
#> name barcode01 barcode02 barcode03
#> <chr> <dbl> <dbl> <dbl>
#> 1 Escherichia 0.2 0.2 0.4
#> 2 Bacteria 0.6 0.3 0.1
创建于 2023-11-08,使用 reprex v2.0.2
也许您需要在上一步中将矩阵强制为类数据框。
数据:
data <- read.table(text = " barcode name fraction
1 barcode01 Escherichia 0.2
2 barcode01 Bacteria 0.6
3 barcode02 Escherichia 0.2
4 barcode02 Bacteria 0.3
5 barcode03 Escherichia 0.4
6 barcode03 Bacteria 0.1", header = TRUE)