2017-04-03 69 views
1

的相应值的数据帧的各列我有以下的数据帧和向量:乘以一个向量

dframe <- as.data.frame(matrix(1:9,3)) 
vector <- c(2,3,4) 

我想通过vector对应的值相乘的dframe每一列。这样不行:

> vector * dframe 
    V1 V2 V3 
1 2 8 14 
2 6 15 24 
3 12 24 36 

每个dframe是由vector相应的值,而不是每个相乘。有没有任何习惯解决方案,或者我坚持for周期?

+1

什么'T(T(DFRAME) *矢量) '? –

+0

这是重复的。一种方法是'df * rep(vec,each = nrow(df))' – lmo

回答

2

下面是使用另一种选择sweep

sweep(dframe, 2, vector, "*") 
# V1 V2 V3 
#1 2 12 28 
#2 4 15 32 
#3 6 18 36 

或者使用col

dframe*vector[col(dframe)] 
+1

我最喜欢第二种选择。我认为这样会更快,如果你迷上了,并且想要在一系列类似的操作上尝试一下:)在我的例子中,在将'dframe'乘以'vector'后,我还想为它添加'center'(另一个矢量)。有了这个方法,我可以写'vec2mat < - col(dframe); dframe * vector [vec2mat] + center [vec2mat]'。 – DeltaIV

1

您可以使用Map

as.data.frame(Map(`*`, dframe, vector)) 

# V1 V2 V3 
#1 2 12 28 
#2 4 15 32 
#3 6 18 36