[R] Data replacement

Dieter Menne dieter.menne at menne-biomed.de
Tue Jan 5 18:19:57 CET 2010




Lisa wrote:
> 
> I have a dataset that looks like this: 
> 
>> data
>          id    code1    code2 
> 1         1        1        4 
> 2         1        2        3 
> 3         2        4        4 
> ..
> 
> I want to change some numbers in the columns of “code1” and “code2” based
> on “indx” as below
> 
>> indx
> [[1]]
>         code 
> 1          1 
> 2          3 
> 3          4 
> For example,  for the first ten records (rows) of my dataset, I want to
> change 2 to 3, 3 to 4, 4 to 6, and 5 to 8 in both “code1” and “code2”,
> while for the last ten records, I want to change 3 to 4 and 4 to 6.
> 
> 

You might check for "recode", for example in package car, or for
"transform". You could also do it the quick and dirty way, good to learn
indexing. Be careful if you have NA in your data, or data out of the recode
range.

Dieter


data = data.frame(code1=sample(1:5,10,TRUE),code2=sample(1:5,10,TRUE))
data =
rbind(data,data.frame(code1=sample(1:4,10,TRUE),code2=sample(1:4,10,TRUE)))

# The recode table as  in your example
#indx = list(data.frame(code=c(1,3,4,6,8)),data.frame(code=c(1,2,4,6)))

#easier to read
recode1 = c(1,3,4,6,8)
recode2 = c(1,2,4,6)

data$code1T[1:10] = recode1[data$code1[1:10]]
data$code2T[1:10] = recode1[data$code2[1:10]]

data$code1T[11:20] = recode2[data$code1[11:20]]
data$code2T[11:20] = recode2[data$code2[11:20]]




-- 
View this message in context: http://n4.nabble.com/Data-replacement-tp999060p999176.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list