2014-01-29 74 views
0

我有兩個dataframes: DF1- [R乘以列由值在第二數據幀

plot grass moss rock other  stuff 
a  4  0  0  text  3 
b  2  2  3  text  4 
c  10  0  0  text  0 
d  3  1  0  text  9 

和 DF2

Cover value 
grass 5 
moss 2 
rock 3 

我想通過在DF2中的相應值乘以在DF1的值。 該解決方案應適用於大型數據集。

結果 DF3

plot grass moss rock  
a  20  0  0  
b  10  4  9  
c  50  0  0  
d  15  2  0  
+6

我的印象是,您希望將'df1'中的'grass'列乘以'df2'中的因子,等等''df2'中的其他變量。如果是這種情況,這並不反映在你的'df3'中。 –

+0

修好了,道歉! – mace

回答

3

您的數據:

df1 <- read.table(
    text = 
    "plot grass moss rock other  stuff 
    a  4  0  0  text  3 
    b  2  2  0  text  4 
    c  10  0  0  text  0 
    d  3  1  0  text  9", 
    header = TRUE 
) 

df2 <- read.table(
    text = 
    "Cover value 
    grass 5 
    moss 2 
    rock 3", 
    header   = TRUE, 
    stringsAsFactors = FALSE 
) 

(確保Cover是一個特徵向量,不是一個因素,對於這個解決方案)

簡單for循環是訣竅:

df3 <- df1 
for(i in seq_len(nrow(df2))) 
{ 
    df3[, df2$Cover[i]] <- df2$value[i] * df1[, df2$Cover[i]] 
}