[R] About change columns and specific rows in R
William Michels
wjm1 at caa.columbia.edu
Tue May 23 08:45:29 CEST 2017
Hi Lily,
You're on the right track, but you should define a new column first
(filled with NA values), then specify the precise rows and columns on
both the left and right hand sides of the assignment operator that
will be altered. Luckily, this is pretty easy...just remember to use
which() on the right hand side of the assignment operator to get the
index of the rows you want. Example below for "product1":
> DF$product1_1 <- NA
> DF[DF$month == 1, "product1_1"] <- DF[which(DF$month == 1), "product1"]*3.1
>
HTH,
Bill.
William Michels, Ph.D.
On Mon, May 22, 2017 at 9:56 PM, lily li <chocold12 at gmail.com> wrote:
> Hi R users,
>
> I have a question about manipulating the dataframe. I want to create a new
> dataframe, and to multiply rows with different seasons for different
> constants.
>
> DF
> year month day product1 product2 product3
> 1981 1 1 18 56 20
> 1981 1 2 19 45 22
> 1981 1 3 16 48 28
> 1981 1 4 19 50 21
> 1981 2 1 17 49 25
> 1981 2 2 20 47 23
> 1981 2 3 21 52 27
>
> For example, how to multiply product1 in month1 by 3.1, and to multiply
> product3 in month2 by 2.0? I wrote the code like this but does not work.
> Thanks for your help.
>
> DF['month'==1, ]$product1_1 = DF['month'==1, ]$product1 * 3.1;
> DF['month'==2, ]$product3_1 = DF['month'==1, ]$product3 * 2.0;
>
> [[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