[R] Changing column names by unique factor levels

Abhinaba Roy abhinabaroy09 at gmail.com
Sat Dec 19 20:26:03 CET 2015


Hi R helpers,

I am stuck with a very strange problem.

My input data is

structure(list(Date = structure(c(1447007400, 1447007400, 1447093800,
1447093800), tzone = "", class = c("POSIXct", "POSIXt")), Prod = c("Colg",
"P&G", "Colg", "P&G"), Amt = c(57, 11, 62, 77), Amt1 = c(86,
72, 20, 23), Amt2 = c(42, 55, 30, 13), Amt3 = c(75, 12, 13, 23
)), .Names = c("Date", "Prod", "Amt", "Amt1", "Amt2", "Amt3"), row.names =
c(NA,
-4L), class = "data.frame")

And, my output data should look like

structure(list(Date = structure(c(1447007400, 1447093800), tzone = "",
class = c("POSIXct",
"POSIXt")), Colg_Amt = c(55, 88), Colg_Amt1 = c(34, 47), Colg_Amt2 = c(63,
36), Colg_Amt3 = c(98, 14), P.G_Amt = c(13, 89), P.G_Amt1 = c(35,
44), P.G_Amt2 = c(90, 64), P.G_Amt3 = c(22, 12)), .Names = c("Date",
"Colg_Amt", "Colg_Amt1", "Colg_Amt2", "Colg_Amt3", "P.G_Amt",
"P.G_Amt1", "P.G_Amt2", "P.G_Amt3"), row.names = c(NA, -2L), class =
"data.frame")

The problem to be solved is that I would like the final data to have the
column names prefixed by the Prod values. I think it can be done using
dcast, but not sure how to use it efficiently.

How can I do this in R?

Thanks,
Abhinaba

	[[alternative HTML version deleted]]



More information about the R-help mailing list