在R中存储多维索引和对应值的最佳方法 [英] Best way to store multidim index and corresponding value in R

查看:77
本文介绍了在R中存储多维索引和对应值的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个维度的索引列表;

I have a list of indexes in 3 dimensions;

> head(TW_idx, n = 4)
[[1]]
[1]   1   1 135

[[2]]
[1]  1  2 96

[[3]]
[1]   1   3 120

[[4]]
[1]   1   1 135

每个索引对应的值为100.但是,一个索引在 TW_idx 中(这里在列表1和4中)可以出现多次,并且每次出现索引时,该值都会增加线性(因此,如果一个索引存在3次,则该索引的值为300).我想找到一种方法来存储索引及其相应的值.

Each index corresponds to a value of 100. However, one index can occur more than one times in TW_idx (here in list 1 and 4) and for each occurence of the index, the value increases linearly (so if one index is present 3 times, the value of that index is 300). I want to find a way to store the index with its corresponding value.

我的想法是我们创建一个看起来像

My thought is that we create a dataframe which would look smth like

> df
 idx    value
1,1,135  200
1,2,96   100
1,3,120  100

对于上述4个值,

但我不确定如何创建它.更好的是,如果我得到的输出是索引只是没有重复的相同列表(即TW_idx<-unique(TW_idx)),并且值存储在长度相同的列表/数字列表中,其中每个元素都描述了该值新(无重复)TW_idx列表中对应元素的值.但是,如果更简单地获取数据框,我将对此感到非常满意.

for the 4 values above but I am not sure how to create it. Even better would be if I could get an output where the indexes are just the same list without duplicates (i.e. TW_idx <- unique(TW_idx) ) and the values are stored in a list/numeric list of the same length where each element describes the value for the corresponding element in the new (without duplicates) TW_idx list. But if it is simpler to get the dataframe, I would be very happy with that.

预先感谢

推荐答案

够了吗?基本上,我从每个列表元素创建一个字符变量.假定它们被一致地记录下来.计算每种组合发生的次数很简单.现在结果是原始计数,但实际上并没有阻止您将其乘以100的情况.

Is this enough? Basically I create a character variable from each list element. It is assumed that they are consistently written down. It is trivial to count the number of times each combination occurs. Right now the result is in raw count but there's really nothing stopping you to multiply this by 100.

x <- list(c(1, 1, 135),
         c(1, 2, 96),
         c(1, 3, 120),
         c(1, 1, 135))

out <- as.data.frame(table(sapply(x, FUN = paste, collapse = ",")))
out

     Var1 Freq
1 1,1,135    2
2  1,2,96    1
3 1,3,120    1

如果您需要列表形式的数据,则可以按行对其进行拆分.

If you need the data in a list form, you can split it row-wise.

split(out, 1:nrow(out))

$`1`
     Var1 Freq
1 1,1,135    2

$`2`
    Var1 Freq
2 1,2,96    1

$`3`
     Var1 Freq
3 1,3,120    1

这篇关于在R中存储多维索引和对应值的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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