Friday, 15 May 2015

Replace dummy output with another value on same row whenever value equal to 1 in R -



Replace dummy output with another value on same row whenever value equal to 1 in R -

looking simple way re-create val variable in of line.x (could 100s of line.x) variables 1 every row. in end line.x variables value of 1 should replaced val decimal value on same row. thanks!

usr_id line.1 line.2 line.3.line.4 line.5 line.6 line.7 line.8 line.9 val 210 1 0 0 0 0 0 0 0 0 21.343 213 0 0 1 0 0 0 0 0 0 2.340 34 0 0 0 0 0 0 0 0 1 23.760 5433 1 0 0 0 0 0 0 0 0 0.300

to this:

usr_id line.1 line.2 line.3.line.4 line.5 line.6 line.7 line.8 line.9 val 210 21.343 0 0.00 0 0 0 0 0 0.00 21.343 213 0.000 0 2.34 0 0 0 0 0 0.00 2.340 34 0.000 0 0.00 0 0 0 0 0 23.76 23.760 5433 0.300 0 0.00 0 0 0 0 0 0.00 0.300

here fictitious info set:

df1 <- read.table(textconnection("usr_id,line.1,line.2,line.3 line.4,line.5,line.6,line.7,line.8,line.9,val 210,1,0,0,0,0,0,0,0,0,21.343 213,0,0,1,0,0,0,0,0,0,2.34 34,0,0,0,0,0,0,0,0,1, 23.76 5433,1,0,0,0,0,0,0,0,0,0.3"), sep=",", header=true)

if values in line.x 1 or 0, work:

result <- df1[,-c(1,ncol(df1))]*df1$val result <- with(df1,data.frame(usr_id,result,val)) result # usr_id line.1 line.2 line.3 line.4 line.5 line.6 line.7 line.8 line.9 val # 1 210 21.343 0 0.00 0 0 0 0 0 0.00 21.343 # 2 213 0.000 0 2.34 0 0 0 0 0 0.00 2.340 # 3 34 0.000 0 0.00 0 0 0 0 0 23.76 23.760 # 4 5433 0.300 0 0.00 0 0 0 0 0 0.00 0.300

r

No comments:

Post a Comment