On Mon, 2007-03-12 at 18:55 +0100, Sergio Della Franca
wrote:> Dear R-helpers,
>
> I'm trying to create a string-code to modify the contents of a column
of a
> matrix.
>
> For example, I have this dataset:
>
> YEAR PRODUCTS
> 1992 3253
> 1993 4144
> 1994 3246
> 1996 4144
> 1997 4087
> 1998 3836
> 1999 4379
> 2000 4072
> 2001 4202
> 2002 4554
> 2003 4456
> 2004 4738
> 2005 4144
>
> I want to convert/update the values of the column "PRODUCTS"
under some
> condition (i.e. when the values of PRODUCTS is greather than 4000 replace
> the values of PRODUCTS whit 0 else replace with 1).
>
> My question is the following:
> there is a function or a metodology that allow to makes this operation?
>
>
> Thank you in advance,
> Sergio
If the data is above is matrix (MAT) and not a data frame:
# See ?cbind and ?ifelse
MAT <- cbind(MAT, NewCol = ifelse(MAT[, "PRODUCTS"] > 4000, 0,
1))
> MAT
YEAR PRODUCTS NewCol
1 1992 3253 1
2 1993 4144 0
3 1994 3246 1
4 1996 4144 0
5 1997 4087 0
6 1998 3836 1
7 1999 4379 0
8 2000 4072 0
9 2001 4202 0
10 2002 4554 0
11 2003 4456 0
12 2004 4738 0
13 2005 4144 0
If it is a data frame:
DF$NewCol <- ifelse(DF$PRODUCTS > 4000, 0, 1)
> DF
YEAR PRODUCTS NewCol
1 1992 3253 1
2 1993 4144 0
3 1994 3246 1
4 1996 4144 0
5 1997 4087 0
6 1998 3836 1
7 1999 4379 0
8 2000 4072 0
9 2001 4202 0
10 2002 4554 0
11 2003 4456 0
12 2004 4738 0
13 2005 4144 0
HTH,
Marc Schwartz