[R] replace

Marc Schwartz marc_schwartz at me.com
Tue Mar 14 00:33:16 CET 2017


> On Mar 13, 2017, at 5:53 PM, Val <valkremk at gmail.com> wrote:
> 
> HI all,
> 
> if first name  is  Alex then I want concatenate the second column to Alex
> to produce Alex and  the second column value
> 
> DF1 <- read.table(header=TRUE, text='first YR
> Alex    2001
> Bob     2001
> Cory    2001
> Cory    2002
> Bob     2002
> Bob     2003
> Alex    2002
> Alex    2003
> Alex    2004')
> 
> 
> Output
> data frame
> DF2
> Alex-2001   2001
> Bob             2001
> Cory            2001
> Cory            2002
> Bob             2002
> Bob             2003
> Alex-2002   2002
> Alex-2003   2003
> Alex-2004   2004
> 
> I tried this one but did not work.
> DF1$first[DF1$first=="Alex"] <-  paste(DF1$first, DF1$YR, sep='-')
> 
> Thank you in advance


Hi,

See ?ifelse and try this:

DF1$Comb <- ifelse(DF1$first == "Alex", 
                   paste(DF1$first, DF1$YR, sep = "-"), 
                   as.character(DF1$first))

> DF1
  first   YR      Comb
1  Alex 2001 Alex-2001
2   Bob 2001       Bob
3  Cory 2001      Cory
4  Cory 2002      Cory
5   Bob 2002       Bob
6   Bob 2003       Bob
7  Alex 2002 Alex-2002
8  Alex 2003 Alex-2003
9  Alex 2004 Alex-2004


Note the coercion of the second returned value to character, otherwise you get the numeric code associated with the factor levels of DF1$first.

I generally try to avoid overwriting the source data, or in this case, column, to preserve it for future use as may be needed.

Regards,

Marc Schwartz



More information about the R-help mailing list