[R] Changing column names by unique factor levels

Bert Gunter bgunter.4567 at gmail.com
Sun Dec 20 00:33:53 CET 2015


1. Why do you think this is a "very strange" problem?

2. Your minimal example is helpful, but confusing: the entries in the
2nd table appear to have nothing to do with the first. I'll assume
that it's just the *form* that you want to show. Also, your
specification may be incomplete: Do the rows continue to alternate in
this regular way? Are there just a few unique products or many?
Assuming regularity and just a few unique products, then simple
indexing is all that's necessary.

Let your original frame be name df. Then

n<- seq_len(nrow(df))
new.df <-cbind(df[n%%2 ==1,-2],df[n%%2==0,-(1:2)])
names(new.df)[-1]<-
as.vector(t(outer(unique(df$Prod),names(df)[-(1:2)],paste,sep="_")))


produces a new.df with the entries from df and the form of your second
data frame. Is that what you want??
If so, great! If not, someone else will have to help, as I don't care
to waste time chasing poorly phrased questions.

Cheers,
Bert


Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sat, Dec 19, 2015 at 11:26 AM, Abhinaba Roy <abhinabaroy09 at gmail.com> wrote:
> 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]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list