重複の可能性:
他のデータ フレームの関数から新しいデータ フレームを作成する
SOF に関する最初の質問で少し助けになりましたが、回答者への回答方法がわかりません。というわけで、再度サンプルコードを載せて投稿します(初めてやるべきだった - 勉強中です)。
2 つのデータ フレームがあります。説明のためにふりをしましょう:
df1 列は収穫の種類を表します: とうもろこし、オートムギ、小麦など。
df2 国を表す列: スペイン、チリ、メキシコなど。このフレームの行は追加費用を表します。おそらく、各国の梱包費、送料、国の輸入税、検査料などです。
次に、3 番目のデータ フレームを作成します。
df3 各月の穀物の組み合わせの総コスト (たとえば、10% のトウモロコシ、50% のオーツ麦など) と、各国の関連する送料、税金などのコストを表します。(df1 と df2 からのデータを使用して) 方程式があると仮定して、与えられた穀物の組み合わせに対する 1 か月あたりの国ごとの総コストと、各国の追加コストを計算します。
つまり、df3 には 12 行 (月) と、国の数と同じ数の列があります。その要素は、各月の穀物の総コスト + 各国のコストです。
Excel/Gnumeric で 2 分、Fortran または C で 15 分、R クックブックとインターネット検索で 2 日間苦労しました。そして、廊下に「やあ、ケビン、R でこれをどうやってやるの?」と叫ぶ人は誰もいません。
とてもシンプルですが、初心者にとっては、いくつかの基本的な点を見落としています..
事前に感謝します。これが私の問題を示す私のふりコードです。
エド
# build df1 - cost of grains (with goofy data so I can track the arithemetic)
v1 <- c(1:12)
v2 <- c(13:24)
v3 <- c(25:36)
v4 <- c(37:48)
grain <- data.frame("wheat"=v1,"oats"=v2,"corn"=v3,"rye"=v4)
grain
# build df2 - additional costs (again, with goofy data to see what is being used where and when)
w1 <- c(1.3:4.3)
w2 <- c(5.3:8.3)
w3 <- c(9.3:12.3)
w4 <- c(13.3:16.3)
cost <- data.frame("Spain"=w1,"Peru"=w2,"Mexico"=w3,"Kenya"=w4)
row.names(cost) <- c("packing","shipping","tax","inspection")
cost
# assume 10% wheat, 30% oats and 60% rye with some clown-equation for total cost
# now for my feeble attemp at getting a dataframe that has 12 rows (months) and 4 column (countries)
total_cost <- data.frame( 0.1*grain[,"wheat"] +
0.3*grain[,"oats"] +
0.6*grain[,"rye"] +
cost["packing","Mexico"] +
cost["shipping","Mexico"] +
cost["tax","Mexico"] +
cost["inspection","Mexico"] )
total_cost
# this gives the correct values for the total cost for Mexico, for each month.
# and if I plug in the other countries, I get correct answers for that country
# I guess I can run a loop over the counties, but this is R, not Fortran or C.
# btw, my real equation is considerably more complicated, using functions involving
# multiple columns of df1 and df2 data, so there is no "every column of a df1 get
#multipied by... or any one-to-one column-row matches.