Chuck Carey
2009-Aug-28 20:43 UTC
[R] sub using info from pattern in 2nd col into part of pattern in 1st column?
I have two data.frame columns and I want to replace part of the first column with the second column : temp<-data.frame(matrix(c("54E5","7","56D7","E3","56F12","14","56F3","10","57C5",NA,"59A1","3"), ncol = 2)) if the 2nd column consists entirely of digits (1 or 2 digits) I want to replace the last digit(s) in the first column with the digits in the second column so ... 54E5 7 56D7 E3 56F12 14 56F3 10 57C5 NA 59A1 3 generates a new column where some values are replaced : 54E7 56D7 56F14 56F10 57C5 59A3 I can pick out the digits in the 2nd column just fine. But instead of 'xxx' below: sub("^([0-9]{1,2})$","xxx\\1",temp$X2, perl = TRUE) ? How can I sub with what I want from the first column ? Thanks for your help! -chuck (Actually, I also want to do a similar thing where E3 in the second row replaces D7 so 56D7 becomes 56E3, pattern of first column is always [0-9]{1,2}[A-F][0-9]{1,2} , but I'd be happy to just deal with the original stated problem for now as it handles most of my cases)