Reshaping data

#1
Hi,

I have a data frame which looks like :

PHP:
          Jan_V Jan_S Feb_V Feb_S    
1         100   90    120   110
2         123   88    112   120
3         121   89    134   130
There are around 200 rows.

The data frame can have additional month columns i.e. Mar_V Mar_S - I don't know this in advance. All I know is that the columns will arrive in pairs i.e. _V and _S.

I need to loop through the column pairs and put each pair of _V and _S into an array of 2 column matrices

The data is held in : data

I've tried the following

PHP:
width <- c(ncol(data) -2)

x <-1

for (set in  1:width){

y <- x +1 

newshape[set] <-cbind(data[, x], data[,y])
x <- x + 2
}
I get an error : newshape not found

It it possible to store an array of matrix's?
 

JesperHP

TS Contributor
#2
Not sure whether this is helpful:
Code:
data=data.frame(JanV=c(1,2,3),JanS=c(4,5,6),FebV=c(7,8,9),FebS=c(10,11,12))
array(as.matrix(data),dim=c(dim(data)[1],2,dim(data)[2]/2))
you cannot index the object >>newshape<< before it has been created... so possible solution if you want to use loop (probably not the way to go) would be to create newshape object outside loop.

If you can get your data as a matrix to start with you can avoid the as.matrix(data) forced conversion which will be timesaving.
 
Last edited:

trinker

ggplot2orBust
#3
I may be misunderstanding, but is this maybe what you want:

Code:
dat <- read.table(text="          Jan_V Jan_S Feb_V Feb_S     
1         100   90    120   110 
2         123   88    112   120 
3         121   89    134   130", header=TRUE)

nc <- ncol(dat)
locs <- split(1:nc, rep(1:c(nc/2), each=2))

setNames(lapply(locs, function(i) {
    stack(dat[, i])
}), gsub("_V", "", names(dat)[sapply(locs, "[", 1)]))

[COLOR="gray"]## $Jan
##   values   ind
## 1    100 Jan_V
## 2    123 Jan_V
## 3    121 Jan_V
## 4     90 Jan_S
## 5     88 Jan_S
## 6     89 Jan_S
## 
## $Feb
##   values   ind
## 1    120 Feb_V
## 2    112 Feb_V
## 3    134 Feb_V
## 4    110 Feb_S
## 5    120 Feb_S
## 6    130 Feb_S[/COLOR]
Never mind, after careful reading I think Jesper has it.
 
#4
Thanks guys - I'll take your suggestions into account.

Jesper - I find it interesting that you think loops aren't the way to go.

Are there other constructs in R that do a better job than loops?