amunategui
amunategui

Reputation: 1220

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

Looking for a simple way to copy the VAL variable in any of the LINE.x (could be 100s of LINE.x) variables that are 1 for every row. In the end all the LINE.x variables with a value of one should be replaced by the VAL decimal value on that 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 is the fictitious data 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)

Upvotes: 0

Views: 51

Answers (1)

jlhoward
jlhoward

Reputation: 59385

If the values in LINE.x are always 1 or 0, then this will 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

Upvotes: 1

Related Questions