1

I have a dataframe consisting of unique entries along the rows, descriptive characteristics for each entry in the first 8 columns, and then week-to-week prices in the columns afterwards. I would like to create a new dataframe that shows the same structure with week-to-week differences in prices in the non-descriptive columns.

So for instance, the 9th column would now show (Week 2 price - Week 1 price) instead of the current Week 1 price. I am having trouble figuring out how to iterate and wondering if it is even necessary to iterate. I am trying to apply seq_len but am not very familiar with the function.

Thanks for your help.

EDIT: Below is example dataframe. The output I hope for is the second structure.

structure(list(s = structure(1:3, .Label = c("aa", "bb", "cc"
), class = "factor"), w1 = c(3, 4, 5), w2 = c(55, 2, 1), w3 = c(52, 
9, 3)), .Names = c("s", "w1", "w2", "w3"), row.names = c(NA, 
-3L), class = "data.frame")

structure(list(s = structure(1:3, .Label = c("aa", "bb", "cc"
), class = "factor"), w1d = c(NA, NA, NA), w2d = c(52, -2, -4
), w3d = c(-3, 7, 2)), .Names = c("s", "w1d", "w2d", "w3d"), row.names = c(NA, 
-3L), class = "data.frame")
Arun
  • 116,683
  • 26
  • 284
  • 387
Z_D
  • 797
  • 2
  • 12
  • 30
  • http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – rmuc8 Apr 07 '15 at 22:12
  • Added an example, thanks. – Z_D Apr 07 '15 at 22:21
  • Try `df2 <- transform(df1, w3d=w3-w2)` – Khashaa Apr 07 '15 at 22:31
  • Thanks. I see that adds one of the difference columns, but I am trying to find a way to do it for all column pairs. So it would also add w2d=w2-w1, but not in a manual way because I have many columns. – Z_D Apr 07 '15 at 22:36
  • `df2 <- df1[1]; for(i in 3:ncol(df1)) df2[paste0("w", i-1,"d")] <- df1[i]-df1[i-1]` Something like this might work. – Khashaa Apr 07 '15 at 23:03

1 Answers1

1

Extracting the numeric columns [2:4] from your data frame, and applying diff by rows give

d <- t(apply(df1[2:4], 1, diff))
     w2 w3
[1,] 52 -3
[2,] -2  7
[3,] -4  2

Combine it to non-numeric columns of your data

df2 <- cbind(df1[1], d)
ExperimenteR
  • 4,453
  • 1
  • 15
  • 19