创建具有不同行尺寸的表 [英] Creating table with different row dimensions

查看:103
本文介绍了创建具有不同行尺寸的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的表:

Let's say I got a table like this:

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"

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

Now I want to manipulate the data so it looks like this:

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

R 中是否可以执行此操作?我应该尝试另一种访问我的数据的方法吗?

Is there a way to do this in R or is it just impossible and should I try another way of getting access to my data?

推荐答案

使用可以非常接近分割。这将返回带有所需值的列表,然后可以使用 lapply 或任何其他列表操作函数:

You can get very close by using split. This returns a list with the values you wanted and you can then use lapply or any other list manipulation function:

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

$ALL
[1] "9"

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

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

如果必须具有矩阵格式的输出,则建议您使用NA填充简短向量:

If you must have the output in matrix format, then I suggest you pad the short vectors with 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"

这篇关于创建具有不同行尺寸的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆