Reorganise 2x36 dataframe to a 6x6 dataframe. Dice throw visualisation

核能气质少年 提交于 2019-12-13 02:37:31

问题


I've created a data-frame of all the possible outcomes from a dice throw as 2x36 dataframe.

    d1  d2
1   1   1
2   2   1
3   3   1
4   4   1
5   5   1
6   6   1
7   1   2
8   2   2
9   3   2
10  4   2
11  5   2
12  6   2
13  1   3
14  2   3
15  3   3
16  4   3
17  5   3
18  6   3
19  1   4
20  2   4
21  3   4
22  4   4
23  5   4
24  6   4
25  1   5
26  2   5
27  3   5
28  4   5
29  5   5
30  6   5
31  1   6
32  2   6
33  3   6
34  4   6
35  5   6
36  6   6

To make this visually more pleasing I want to re-organise it as a 6x6 table.

   [,1]  [,2]  [,3]  [,4]  [,5]  [,6] 
[1,] "1 1" "1 2" "1 3" "1 4" "1 5" "1 6"
[2,] "2 1" "2 2" "2 3" "2 4" "2 5" "2 6"
[3,] "3 1" "3 2" "3 3" "3 4" "3 5" "3 6"
[4,] "4 1" "4 2" "4 3" "4 4" "4 5" "4 6"
[5,] "5 1" "5 2" "5 3" "5 4" "5 5" "5 6"
[6,] "6 1" "6 2" "6 3" "6 4" "6 5" "6 6"

How would I achieve this?


回答1:


Here is a base R alternative using lapply and apply

out =  do.call(rbind,
                lapply(split(data, data$d2),function(x) 
                apply(x, 1, function(y) paste(y['d2'], y['d1'], collapse = ' '))
               )
#>out                
#     1     2     3     4     5     6    
#1 "1 1" "1 2" "1 3" "1 4" "1 5" "1 6"
#2 "2 1" "2 2" "2 3" "2 4" "2 5" "2 6"
#3 "3 1" "3 2" "3 3" "3 4" "3 5" "3 6"
#4 "4 1" "4 2" "4 3" "4 4" "4 5" "4 6"
#5 "5 1" "5 2" "5 3" "5 4" "5 5" "5 6"
#6 "6 1" "6 2" "6 3" "6 4" "6 5" "6 6"



回答2:


We can paste the columns and use matrix specifying the dimensions

matrix(do.call(paste, df1), ncol=6)
#     [,1]  [,2]  [,3]  [,4]  [,5]  [,6] 
#[1,] "1 1" "1 2" "1 3" "1 4" "1 5" "1 6"
#[2,] "2 1" "2 2" "2 3" "2 4" "2 5" "2 6"
#[3,] "3 1" "3 2" "3 3" "3 4" "3 5" "3 6"
#[4,] "4 1" "4 2" "4 3" "4 4" "4 5" "4 6"
#[5,] "5 1" "5 2" "5 3" "5 4" "5 5" "5 6"
#[6,] "6 1" "6 2" "6 3" "6 4" "6 5" "6 6"

If there are only two columns, we can also paste by subsetting the columns individually

matrix(paste(df1[,1], df1[,2]), ncol = 6)

If you need a dcast/acast approach, create another column by pasteing the columns of 'df1' and then do the acast.

library(reshape2)
acast(data.frame(df1, value=do.call(paste, df1), stringsAsFactors=FALSE), ar~br)
#    1     2     3     4     5     6    
#1 "1 1" "1 2" "1 3" "1 4" "1 5" "1 6"
#2 "2 1" "2 2" "2 3" "2 4" "2 5" "2 6"
#3 "3 1" "3 2" "3 3" "3 4" "3 5" "3 6"
#4 "4 1" "4 2" "4 3" "4 4" "4 5" "4 6"
#5 "5 1" "5 2" "5 3" "5 4" "5 5" "5 6"
#6 "6 1" "6 2" "6 3" "6 4" "6 5" "6 6"

Or a similar option using spread from tidyr

library(dplyr)
library(tidyr)
df1 %>%
   mutate(value= paste(ar, br)) %>%
   spread(br, value)

But, this can be created directly using outer

outer(1:6, 1:6, FUN= paste)

data

df1 <- expand.grid(ar=1:6, br=1:6)


来源:https://stackoverflow.com/questions/32271810/reorganise-2x36-dataframe-to-a-6x6-dataframe-dice-throw-visualisation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!