crumbly - 2 months ago 22

R Question

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

Answer

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
```