你怎样从一个矩阵(2D数组)中获取一个数据框?

huangapple go评论61阅读模式
英文:

How can I obtain a dataframe from a matrix (2D-array)?

问题

Trend Cluster
1 5
2 4
3 2
4 1
5 2
6 4
7 1
8 2
9 2
10 5
11 1

英文:

I'd like to transform my array into a dataframe, with the column "Cluster" where there will be the numbers 5,4,2,1, ... and "Trend" with numbers 1,2,3,4,...

           [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] 
  cluster    5    4    2    1    2    4    1    2    2     5     1    

What I expect :

               Trend               Cluster
               1                   5
               2                   4
               3                   2
               4                   1
               ...

答案1

得分: 1

With data.frame:

data.frame(Trend = seq_along(mat), t(mat))

#   Trend cluster
# 1     1       5
# 2     2       4
# 3     3       2

Reproducible data:

mat <- t(c(5, 4, 2))
rownames(mat) <- "cluster"
英文:

With data.frame:

data.frame(Trend = seq_along(mat), t(mat))

#   Trend cluster
# 1     1       5
# 2     2       4
# 3     3       2

Reproducible data:

mat &lt;- t(c(5, 4, 2))
rownames(mat) &lt;- &quot;cluster&quot;

答案2

得分: 0

cluster &lt;- c(5,4,2,1,2,4,1,2,2,5,1);
data.frame('trend' = seq_len(length(cluster)), cluster)

An example: data.frame example

英文:
cluster &lt;- c(5,4,2,1,2,4,1,2,2,5,1);
data.frame(&#39;trend&#39; = seq_len(length(cluster)), cluster)

An example: data.frame example

huangapple
  • 本文由 发表于 2023年4月10日 22:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定