ranell ranell - 1 month ago 8
R Question

Product multiple columns by a single column in a dataframe

My datas as follows:

datas6=structure(list(Exp = c("BA", "CI", "CE", "DE"), Var1 = c(0L,
0L, 0L, 0L), Var2 = c(0L, 0L, 1L, 0L), Var3 = c(0L, 1L, 1L, 0L
), Var4 = c(1L, 1L, 1L, 1L), Freq = c("6", "2", "7", "5")), .Names = c("Exp",
"Var1", "Var2", "Var3", "Var4", "Freq"), row.names = c(NA, 4L
), class = "data.frame")


That's a basic question and I'm sorry for that, can't find a way to multiply from datas6[2] to datas6[5] by datas6[6] such this pseudo code :

datas6[2:5]=as.numeric(datas6[2:5])*as.numeric(datas6[6])


returns error :

Error: object (list) can not be converted automatically into a type 'double'


Tried this also :

new_df <- ddply(datas6, (datas6[2:5]), transform, new_column = as.numeric(datas6[2:5])*as.numeric(datas6[6]))


do not works :
Error in UseMethod("as.quoted"
)

Thanks a lot.

Answer

We can do this by

datas6[2:5] <- datas6[2:5] * as.numeric(datas6[,6])
datas6[2:5]
#   Var1 Var2 Var3 Var4
#1    0    0    0    6
#2    0    0    2    2
#3    0    7    7    7
#4    0    0    0    5
Comments