【问题标题】:Converting matrix from 288*2 to 48*6将矩阵从 288*2 转换为 48*6
【发布时间】:2019-08-19 00:21:39
【问题描述】:

我有结果数据作为列表:

    "ID_station" "val"
"1" 1 405
"2" 1 202.5
"3" 1 11.911
"4" 1 101.25
"5" 1 81
"6" 1 1.7936
"7" 2 11.764
"8" 2 12.5
"9" 2 6.0606
"10" 2 400
"11" 2 12.12
"12" 2 1.844
"13" 4 480
"14" 4 12
"15" 4 43.636
"16" 4 160
"17" 4 96
"18" 4 1.726
"19" 5 11.73
"20" 5 12.272
"21" 5 11.25
"22" 5 270
"23" 5 6
"24" 5 2.05

我需要以这种格式获取结果 - 来自 ID 站的第一列和第二列使矩阵 6*48

1   405       202.5 11.911  101.25  81      1.793
2   11.7647   12.5  6.06    400     12.121  1.844
4   480       12    43.63   160      96     1.7263
5   11.73     12.27 11.25   270      6      2.05

我尝试做类似的事情但失败了

vector_result=as.vector(unlist(result))
V_1=matrix(vector_result, ncol =12)

【问题讨论】:

  • 请为您的 data.frame 提供dput 并将输出粘贴到此处。
  • 你想要6列,你为什么用ncol = 12
  • 您可能必须在矩阵中使用 byrow = T 参数。矩阵(vector_results$val,ncol = 6,byrow = T)

标签: r list dataframe matrix


【解决方案1】:

这在这里有效:

##assume test is structured like you example
Reshaped <- t(sapply(split(test,test$ID.station),function(df){return(df$val)}))

【讨论】:

  • 或者do.call(rbind, split(test$val,test$ID_station))
【解决方案2】:
# Example data
df <- data.frame(ID = rep(1:3, each = 6), value = round(rnorm(18), 2))

# My solution
t(unstack(df, value ~ ID))

#     [,1]  [,2]  [,3]  [,4]  [,5] [,6]
# X1  0.25 -0.10  0.43 -0.75  0.33 0.08
# X2 -0.27  0.80  0.75  0.24 -0.03 2.85
# X3 -0.54 -1.33 -2.12  0.67  0.54 0.02

【讨论】:

  • 非常好的解决方案,我刚刚发现了一个我从未使用过的新功能(unstack)。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 2017-02-21
相关资源
最近更新 更多