Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to multiply data frame by vector?

Tags:

dataframe

r

I'm trying to multiply a data frame df by a vector v, so that the product is a data frame, where the i-th row is given by df[i,]*v. I can do this, for example, by

df <- data.frame(A=1:5, B=2:6); v <- c(0,2) as.data.frame(t(t(df) * v))    A  B 1  0  4 2  0  6 3  0  8 4  0 10 5  0 12 

I am sure there has to be a more R-style approach (and a very simple one!), but nothing comes on my mind. I even tried something like

apply(df, MARGIN=1, function(x) x*v) 

but still, non-readable constructions like as.data.frame(t(.)) are required.
How can I find an efficient and elegant workaround here?

like image 924
tonytonov Avatar asked Aug 22 '13 14:08

tonytonov


People also ask

How do you multiply a data frame?

The mul() method of DataFrame object multiplies the elements of a DataFrame object with another DataFrame object, series or any other Python sequence. mul() does an elementwise multiplication of a DataFrame with another DataFrame, a pandas Series or a Python Sequence.

How do you multiply vector values?

To multiply a vector by a scalar, multiply each component by the scalar. If →u=⟨u1,u2⟩ has a magnitude |→u| and direction d , then n→u=n⟨u1,u2⟩=⟨nu1,nu2⟩ where n is a positive real number, the magnitude is |n→u| , and its direction is d .

How do you create a vector from a data frame?

To create a vector of data frame values by rows we can use c function after transposing the data frame with t. For example, if we have a data frame df that contains many columns then the df values can be transformed into a vector by using c(t(df)), this will print the values of the data frame row by row.


1 Answers

This works too:

data.frame(mapply(`*`,df,v)) 

In that solution, you are taking advantage of the fact that data.frame is a type of list, so you can iterate over both the elements of df and v at the same time with mapply.

Unfortunately, you are limited in what you can output from mapply: as simple list, or a matrix. If your data are huge, this would likely be more efficient:

data.frame(mapply(`*`,df,v,SIMPLIFY=FALSE)) 

Because it would convert it to a list, which is more efficient to convert to a data.frame.

like image 181
nograpes Avatar answered Oct 11 '22 19:10

nograpes