[R] Question on applying vectors to data.frames by row

RDM rdmerrio at amaonline.com
Tue Nov 14 00:36:44 CET 2006


# Newbie alert
# I am wanting to multiply the rows in a dataframe by a vector.
# However, the default behavior appears to be for the vector to be applied
# column wise. For example:

vct <- 1:4
df <- data.frame(c1 = 5:10, c2= 6:11, c3=7:12, c4=8:13)
multTheTwo <- vct * df
multTheTwo

# This results in the vector getting cycled columnwise
#   c1 c2 c3 c4
# 1  5 18  7 24
# 2 12 28 16 36
# 3 21  8 27 10
# 4 32 18 40 22
# 5  9 30 11 36
# 6 20 44 24 52

# But what I actually want is:
#  c1 c2 c3 c4
#1  5 12 21 32    which is 5*1, 6*2, 7*3, 8*4
#2  6 14 24 36    same pattern applied to the next row
#3  7 16 27 40    so on ....
#4  8 18 30 44
#5  9 20 33 48
#6 10 22 36 52

# I am currently using a for statement to do this, but that just doesn't
feel
# right. Is there another option that is more "R" like.

for(i in 1:length(vct)) multTheTwo[,i] <- vct[i] * df[,i]
multTheTwo

# Thanks Richard

--



More information about the R-help mailing list