0

I have the following dataframe u

   u<- data.frame(a=c("x1","x2","x3","x4","x5","x6","x7"),b=c(2005,2006,2007,2008,2009,2010,2011),c1=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),c2=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),c3=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5))
a   b       c1  c2  c3
x1  2005    0.5 0.5 0.5
x2  2006    0.5 0.5 0.5
x3  2007    0.5 0.5 0.5
x4  2008    0.6 0.6 0.6
x5  2009    0.7 0.7 0.7
x6  2010    0.9 0.9 0.9
x7  2011    0.5 0.5 0.5

I want to replace values in column (c1,c2,c3) based on values in column b. So if the value in column b is less than 2008, replace values in column (c1,c2,c3) to 1,2 and 3. The resulting data frame is

 a  b     c1    c2  c3
x1  2005    1   2   3
x2  2006    1   2   3
x3  2007    1   2   3
x4  2008    0.6 0.6 0.6
x5  2009    0.7 0.7 0.7
x6  2010    0.9 0.9 0.9
x7  2011    0.5 0.5 0.5
1
  • 2
    Try u[which(u$b<2008),3:5] <- rep(1:3,each=3) Commented Nov 29, 2016 at 15:03

4 Answers 4

1

Without using libraries, or in case you need to generalize this to many c columns, you can do:

u <- data.frame(a=c("x1","x2","x3","x4","x5","x6","x7"),
b=c(2005,2006,2007,2008,2009,2010,2011),
c1=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),
c2=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),
c3=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5))

Then use normal brackets notation to subset, and assign the three columns at once:

u[u$b<2008,3:5] <- data.frame(1,2,3)
u
   a    b  c1  c2  c3
1 x1 2005 1.0 2.0 3.0
2 x2 2006 1.0 2.0 3.0
3 x3 2007 1.0 2.0 3.0
4 x4 2008 0.6 0.6 0.6
5 x5 2009 0.7 0.7 0.7
6 x6 2010 0.9 0.9 0.9
7 x7 2011 0.5 0.5 0.5
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

library(magrittr)

u$c1 %<>% ifelse(u$b < 2008, 1, .)

u$c2 %<>% ifelse(u$b < 2008, 2, .)

u$c3 %<>% ifelse(u$b < 2008, 3, .)

Comments

0

I happen to find this to be more intuitive but just a preference.

u$c1[u$b < 2008] <- 1 u$c2[u$b < 2008] <- 2 u$c3[u$b < 2008] <- 3

Comments

0

and another way...

library(dplyr)
u %>%
  mutate(c1 = ifelse(b < 2008, 1, c1),
         c2 = ifelse(b < 2008, 2, c2),
         c3 = ifelse(b < 2008, 3, c3)
        )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.