簡體   English   中英

將兩個不同數據框的列相乘

[英]Multiply Columns of two different dataframes

如何有效地將具有相同行數但不同列數的兩個不同數據幀的列相乘。 我有兩個數據集卷和價格,並在欲乘以每個價格列中的每個列體積,使得所得到的數據幀將具有n×m個列(n為ncols在第一數據幀和m是ncols在第二數據幀)。

set.seed(159) # for reproducibility
volumes <- as.data.frame(cbind(Year = 2000:2004, 
                               matrix(round(runif(25, 50, 100), 0), 
                                      nrow = 5, ncol = 5)))
names(volumes) <- c("Year", paste(rep("V", 5), seq(1:5), sep = ""))
volumes
  Year V1 V2 V3 V4 V5
1 2000 56 52 88 81 52
2 2001 81 56 90 76 69
3 2002 81 92 69 93 69
4 2003 56 68 77 80 72
5 2004 51 58 62 53 62

set.seed(159)
prices <-   as.data.frame(cbind(Year = 2000:2004, 
                                matrix(round(runif(20, 5, 15), 0), 
                                       nrow = 5, ncol = 2)))
names(prices) <-  c("Year", paste(rep("P", 2), seq(1:2), sep = ""))
prices
  Year P1 P2
1 2000  6  5
2 2001 11  6
3 2002 11 13
4 2003  6  9
5 2004  5  7

這是一種可能的方法。 它不是效率最高的,但是可以完成工作:

result <- c()
for(i in names(volumes)) {
  for(j in names(prices)) {
    result <- c(result, volumes[i] * prices[j])
  }
}

# outcome of every combination as you want (m * n columns)
result_df <- as.data.frame(result)

# resulting column names are a bit messy but you can rename easily
# names(result_df) <- # your list of m * n names
prices <- structure(list(Year = c(2001, 2003, 2002, 2000, 2004), P1 = c(15, 
8, 13, 12, 7), P2 = c(7, 10, 8, 14, 10)), row.names = c(2L, 4L, 
3L, 1L, 5L), class = "data.frame")

volumes <- structure(list(Year = c(2000, 2001, 2002, 2003, 2004), V1 = c(76, 
78, 55, 74, 80), V2 = c(61, 80, 77, 68, 65), V3 = c(56, 52, 91, 
69, 90), V4 = c(50, 59, 51, 66, 58), V5 = c(75, 57, 57, 80, 59
)), class = "data.frame", row.names = c(NA, -5L))

我們可以使用lapplypurrr::reduce分兩步進行lapply

首先,我們使用lapply遍歷每一列prices然后乘以volumes lapply返回一個列表,並將每個操作的輸出作為列表項。

volumes_mult <- lapply(prices[,-1], function(p) {
    cbind(Year = volumes$Year, volumes[,-1] * p)
})

然后,我們使用reduce*_join操作應用於列表中的每個項目。 我建議使用purrr::reduce而不是base R Reduce因為它可以更輕松地向*_join提供其他參數(我們需要by=參數來正確連接表)。 您還可以自定義suffix=參數以選擇如何重命名來自不同表的相同行:

purrr::reduce(volumes_mult, dplyr::full_join, by='Year', suffix = paste0('_', names(x)))

  Year V1_P1 V2_P1 V3_P1 V4_P1 V5_P1 V1_P2 V2_P2 V3_P2 V4_P2 V5_P2
1 2000  1140   915   840   750  1125   532   427   392   350   525
2 2001   624   640   416   472   456   780   800   520   590   570
3 2002   715  1001  1183   663   741   440   616   728   408   456
4 2003   888   816   828   792   960  1036   952   966   924  1120
5 2004   560   455   630   406   413   800   650   900   580   590

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM