在R中实现数据框列与另一数据框行值的指定乘除运算
解决方案
可以通过矩阵广播运算高效完成批量计算,步骤如下:
- 提取
policy.1中的温度列(排除id列)并转为矩阵格式 - 对所有温度值先乘以100,再按列对应除以
policy.2$time的每个元素 - 将计算结果与原
id列合并,还原为数据框
完整代码:
set.seed(100) policy.1 <- data.frame(id= 1:2450, temperature.1= runif(2450, min=40, max=80), temperature.2= runif(2450, min=10, max=20), temperature.3= runif(2450, min=50, max=70), temperature.4= runif(2450, min=10, max=20), temperature.5= runif(2450, min=10, max=20), temperature.6= runif(2450, min=10, max=20), temperature.7= runif(2450, min=10, max=20), temperature.8= runif(2450, min=10, max=20), temperature.9= runif(2450, min=10, max=20), temperature.10= runif(2450, min=10, max=20), temperature.11= runif(2450, min=10, max=20), temperature.12= runif(2450, min=10, max=20), temperature.13= runif(2450, min=10, max=20), temperature.14= runif(2450, min=10, max=20), temperature.15= runif(2450, min=10, max=20), temperature.16= runif(2450, min=10, max=20), temperature.17= runif(2450, min=10, max=20), temperature.18= runif(2450, min=10, max=20), temperature.19= runif(2450, min=10, max=20), temperature.20= runif(2450, min=10, max=20), temperature.21= runif(2450, min=10, max=20)) policy.2 <- data.frame(year= (2000:2020), time=c(44,55,66,77,88,89,90,91,94,100,105,106,107,111,115,117,120,124,127,130,134)) # 执行计算 temp_matrix <- as.matrix(policy.1[, -1]) # 提取温度列转矩阵 result_matrix <- (temp_matrix * 100) / policy.2$time # 按列对应除法 result_df <- cbind(policy.1[, "id", drop=FALSE], as.data.frame(result_matrix)) # 合并id列 # 查看结果前5行 head(result_df, 5)
代码说明
policy.1[, -1]:排除第一列的id,只保留所有温度列(temp_matrix * 100) / policy.2$time:利用R的广播特性,矩阵的每一列会自动除以policy.2$time中对应的元素(第1列除以第1个time值,第2列除以第2个time值,以此类推)cbind(...):将原id列和计算后的温度列合并,还原为数据框格式
内容的提问来源于stack exchange,提问作者YouLocalRUser
相关产品推荐
相关产品推荐

