提问人:Marwin 提问时间:11/8/2023 最后编辑:PhilMarwin 更新时间:11/8/2023 访问量:39
R 中的数据/矩阵操作 [重复]
Data/matrix manipulation in R [duplicate]
问:
亲爱的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
有人有答案/解决方案吗? 请留意您的来信!
亲切问候 马文
答:
0赞
Friede
11/8/2023
#1
我想你想要
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)
评论