我有兩個數據幀,我希望將一個數據幀的值插入另一個(我們稱之爲DF1
和DF2
)。R使用for()循環來填充另一個數據幀
DF1
由2列1和2列1(col1
)所包含的字符a到z以及col2
具有與每個字符(從a到z)相關聯的值
DF2
是與3列的數據幀。前兩種包括DF1$col1
的所有組合:aa ab ac ad等;其中,第一個字母是col1
,第二個字母是col2
我想創建利用DF1$col2
值的簡單的數學模型,看物體的各種可能組合的結果在DF1$col1
的第一步,我想do的做法是將DF1$col2
的值轉換爲DF2$col3
(DF2$col3
的值應該與DF2col1中的值相關聯),但這是我卡住的地方。我現在有
for(j in 1:length(DF2$col1))
{
## this part is to use the characters in DF2$col1 as an input
## to yield the output for DF2$col3--
input=c(DF2$col1)[j]
## This is supposed to use the values found in DF1$col2 to fill in DF2$col3
g=DF1[(DF1$col2==input),"pred"]
## This is so that the values will fill in DF2$col3--
DF2$col3=g
}
當我運行此,DF2$col3
將具有相同值從DF1
填補了一個特定的字符(如DF2$col3
將有無不洋溢着用字符「a」從DF1
關聯的值的行) 我究竟做錯了什麼?
多謝您的時間
你試過'merge'嗎?請參閱http://stackoverflow.com/q/4878773/210673 – Aaron 2011-06-02 20:36:51
爲什麼自從您提到'col1'和'col2'代表'df1'時,您將'pred'視爲colname? – chl 2011-06-02 21:00:09
這是一個錯誤;我忘了用df1替換pred $ col2〜_〜 – Anon 2011-06-02 21:35:06