Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

How to get total count of repeated values and make an adjacency table

$
0
0

I have similar data

df <- data.frame(city1=sample(c("Tokyo","New York","Los Angeles", "Mumbai", "Los Angeles", "Tokyo", "Shanghai", "Kolkata", "Los Angeles", "Tokyo")),
                     city2=sample(c("Tokyo","Tokyo","Tokyo","Tokyo","New York", "Tokyo",'Mumbai', "Los Angeles", "Kolkata", "Shanghai")),
                     city3=sample(c("Los Angeles", "Mumbai", "Shanghai", "New York", "Kolkata", "Los Angeles","Los Angeles","Shanghai","Los Angeles","Los Angeles")),
                     city4=sample(c("Los Angeles", "Kolkata", "Shanghai", "Kolkata", "Shanghai", "Los Angeles", "Tokyo", "Los Angeles", "Shanghai", "Tokyo")))

Which gives:

     df                    
         city1       city2       city3       city4
1        Tokyo      Mumbai    Shanghai    Shanghai
2      Kolkata       Tokyo      Mumbai Los Angeles
3       Mumbai     Kolkata     Kolkata       Tokyo
4        Tokyo       Tokyo Los Angeles     Kolkata
5        Tokyo       Tokyo Los Angeles     Kolkata
6     New York    Shanghai    Shanghai Los Angeles
7  Los Angeles       Tokyo    New York Los Angeles
8     Shanghai    New York Los Angeles       Tokyo
9  Los Angeles Los Angeles Los Angeles    Shanghai
10 Los Angeles       Tokyo Los Angeles    Shanghai

I want to create two adjacency matrix with following rules. In first matrix, number of connections between cities of first column with rest of columns in all observations (one way-from first column to rest ones), and (2) In second matrix, number of connections between any two cities (two ways). Example of first matrix is similar to:

           Kolkata Los Angeles Mumbai New York Shanghai Tokyo
Kolkata      0
Los Angeles  0
Mumbai       2
New York     0
Shanghai     0
Tokyo        2

Is there any way to do it easily. Would appreciate any help


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>