-2

I have data like below

device  usage
a   10
a   20
b   30
b   14
c   90
c   80
c   66

How do I transform it to below?

device V1 V2 V3
a 10 20
b 30 14
c 90 80 66

I used ddply(ds,~device,paste) converted it to

a,c(10,20)

b,c(30,14)

c,c(90,80,66) 

How do I split vector into columns. Or other method is welcome

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171

1 Answers1

2

You can add a new column and use that for reshape. Calling your original data frame x:

> x$V <- ave(as.numeric(x$device), x$device, FUN=seq_along)
> reshape(x, direction="wide", timevar='V', idvar='device')
  device usage.1 usage.2 usage.3
1      a      10      20      NA
3      b      30      14      NA
5      c      90      80      66

The added column V counts the occurrences of each unique device, which need not be contiguous in the data frame. This is used in the reshape for the timevar.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112