Cinji18
Cinji18

Reputation: 629

R: Multiplying One Column to the Rest of the Data Frame Based on Index/Position

I have this:

Keyword   1    2    3    4   Pos  Bid
a        0.8  0.6  0.4  0.2   1    5
b        0.9  0.7  0.5  0.3   3    9
c        0.6  0.3  0.2  0.1   2    7
d        0.5  0.4  0.4  0.2   4    2

I need to multiple columns 1 through 4 by Bid except for the column indicated by Pos for each row so that I get this:

Keyword     1       2       3       4
a           5     5*0.6   5*0.4   5*0.2
b         9*0.9   9*0.7     9     9*0.3
c         7*0.6     7     7*0.2   7*0.1
d         2*0.5   2*0.4   2*0.4     2

The columns are in fact named as "1", "2", "3", "4", "5", "6", "7", "8", "9", and "10".

Any help would be greatly appreciated.

Thanks.

Upvotes: 2

Views: 430

Answers (1)

David Arenburg
David Arenburg

Reputation: 92300

This seem to work

colindx <- grep("\\d", names(df))
df[, colindx] <- df[, colindx] * df$Bid
df[, colindx][cbind(seq_len(nrow(df)), df$Pos)] <- df$Bid
df
##   Keyword  X1  X2  X3  X4 Pos Bid
## 1       a 5.0 3.0 2.0 1.0   1   5
## 2       b 8.1 6.3 9.0 2.7   3   9
## 3       c 4.2 7.0 1.4 0.7   2   7
## 4       d 1.0 0.8 0.8 2.0   4   2

Some explanations:

grep("\\d", names(df)) selects only the column names that are containing numbers in them and I multiply these column by df$Bid

The second step is to the columns per each row that specified in Pos using cbind(seq_len(nrow(df)), df$Pos) and insert the actual bids into them using <- df$Bid

Upvotes: 1

Related Questions