0

I'm very new to use R language and have some problems sorting the data below to make visualization.

I have a list as follows:

    week    city           price
1   1       newyork        100
2   1       paris          120
3   1       barcelona      130
4   2       paris          100
5   2       barcelona      90
6   2       newyork        80
7   3       newyork        70
8   3       paris          60
9   3       barcelona      50
.   .       .              .
.   .       .              .
.   .       .              .
.   .       .              .
.   .       .              .
.   .       .              .
.   .       .              .

I would like to make the list to a matrix like below

             week1          week2         week3        week4 .....
barcelona    130             90
paris        120             100
newyork      100             80

What is the most efficient way to do this?

I would ideally group the cities as row names, then week numbers as columns and match the price accordingly. I don't know the efficient way to do this yet. I would appreciate your help.

** the data type is list ** week: chr, city: Factor, price: num

tmhs
  • 998
  • 2
  • 14
  • 27
  • 1
    Assuming that the original data is stored in a data.frame named `df1`, try `reshape2::dcast(df1, city ~ week, value.var = "price")`. – RHertel Aug 10 '16 at 03:16
  • @silverrain, are you sure your data is a list? You can check this by using the `class` function. – shayaa Aug 10 '16 at 03:18
  • @shayaa Yes I checked with typeof(df) and it gave me "list" as return. week: chr, city: factor, price: num – tmhs Aug 10 '16 at 04:18
  • @RHertel I changed the list into data frame, and then used the line you suggested, and I got the return "Error in unique.default(x) : unique() applies only to vectors" – tmhs Aug 10 '16 at 04:21
  • ah, Thank you @RHertel reshape was very useful! – tmhs Aug 10 '16 at 04:35
  • @silverrain Good to know that it helped. Is your question solved now or do you need further assistance? Maybe you could specify your data structure more clearly, preferably by posting the output of `dput(x)`. Then one could reopen this question if it turns out that it is not a duplicate of another question. – RHertel Aug 10 '16 at 07:28
  • @silverrain A data.frame is a special type of list. If `x` is a data.frame, `typeof(x)` will return `"list"`, while `class(x)` yields `"data.frame"`. More detailed information is available with `str(x)`. – RHertel Aug 10 '16 at 07:37

0 Answers0