gpt4 book ai didi

r - 创建具有不同行维度的表

转载 作者:行者123 更新时间:2023-12-04 06:26:27 24 4
gpt4 key购买 nike

假设我有一张这样的 table :

data <- c(1,2,3,6,5,6,9,"LC","LC","HC","HC","LC","HC","ALL")
attr(data,"dim") <- c(7,2)
data
[,1] [,2]
[1,] "1" "LC"
[2,] "2" "LC"
[3,] "3" "HC"
[4,] "6" "HC"
[5,] "5" "LC"
[6,] "6" "HC"
[7,] "9" "ALL"

现在我想操作数据,使其看起来像这样:

     [,"LC"] [,"HC"] [,"ALL"] 
[1,] "1" "3" "9"
[2,] "2" "6"
[3,] "5" "6"

有没有办法在 R 中做到这一点,或者这根本不可能,我应该尝试另一种方式来访问我的数据吗?

最佳答案

使用 split 可以非常接近。这将返回一个包含您想要的值的列表,然后您可以使用 lapply 或任何其他列表操作函数:

split(data[, 1], data[, 2])

$ALL
[1] "9"

$HC
[1] "3" "6" "6"

$LC
[1] "1" "2" "5"

如果您必须以矩阵格式输出,那么我建议您用 NA 填充短向量:

x <- split(data[, 1], data[, 2])
n <- max(sapply(x, length))

pad_with_na <- function(x, n, padding=NA){
c(x, rep(padding, n-length(x)))
}

sapply(x, pad_with_na, n)

这导致:

     ALL HC  LC 
[1,] "9" "3" "1"
[2,] NA "6" "2"
[3,] NA "6" "5"

关于r - 创建具有不同行维度的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5988825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com