【发布时间】:2017-03-22 20:28:12
【问题描述】:
这是我在堆栈溢出中的第一篇文章,请原谅任何错误。我对 R 语法和数据表也很陌生。
特别是对于数据表,我想与第五列中的值进行比较,有条件地测试和替换四列中的行值。示例数据如下:
head(loadProfiles)
load_ev_ag load_ev_res load_ev_res_tou load_ev_workplace maxICA
1: 8469.231 2317.895 36700.00 220200.000 8808
2: 8768.000 2609.524 36533.33 36533.333 8768
3: 8744.000 3168.116 27325.00 10409.524 8744
4: 7006.452 3810.526 24133.33 3620.000 8688
5: 5794.595 4660.870 19490.91 2144.000 8576
6: 6057.143 5888.889 16307.69 2208.333 8480
7: 7036.667 7279.310 14073.33 2814.667 8444
8: 8107.692 8107.692 14053.33 3634.483 8432
9: 8138.462 9200.000 11755.56 3992.453 8464
10: 8173.077 10625.000 10119.05 4427.083 8500
我想做的是在前 4 列中的每一列上循环执行以下操作,将每一列与第五列中的值进行比较。
loadProfiles[load_ev_ag >= maxICA, load_ev_ag := maxICA]
我想要的结果应该如下所示:
head(loadProfiles)
load_ev_ag load_ev_res load_ev_res_tou load_ev_workplace maxICA
1: 8469.231 2317.895 8808 8808 8808
2: 8768.000 2609.524 8768 8768 8768
3: 8744.000 3168.116 8744 8744 8744
4: 7006.452 3810.526 8688 3620.000 8688
5: 5794.595 4660.870 8576 2144.000 8576
6: 6057.143 5888.889 8480 2208.333 8480
7: 7036.667 7279.310 8444 2814.667 8444
8: 8107.692 8107.692 8432 3634.483 8432
9: 8138.462 8464 8464 3992.453 8464
10: 8173.077 8500 8500 4427.083 8500
我尝试了以下方法,但没有成功:
loadProfileNames <- colnames(loadProfiles)[1:4]
loadProfiles[i = (loadProfileNames) >= maxICA,j = (loadProfileNames) := maxICA]
这会产生以下警告,并将前四列中的所有值更改为第五列中的值
Warning message:
In (loadProfileNames) >= maxICA :
longer object length is not a multiple of shorter object length
我还尝试了以下操作,将满足 i = (loadProfileNames) >= maxICA 条件的 x 行的子集更改为 maxICA 中的前 x 个条目,而不是 maxICA 中与 x 行子集中的第 i 行对应的值
for(j in loadProfileNames) { set(loadProfiles,i=which(loadProfiles[[j]] >= loadProfiles[["maxICA"]]),j=j,value=loadProfiles[["maxICA"]]) }
并产生以下警告
Warning messages:
1: In set(loadProfiles, i = which(loadProfiles[[j]] >= loadProfiles[["maxICA"]]), :
Supplied 288 items to be assigned to 24 items of column 'load_ev_ag' (264 unused)
2: In set(loadProfiles, i = which(loadProfiles[[j]] >= loadProfiles[["maxICA"]]), :
Supplied 288 items to be assigned to 108 items of column 'load_ev_res' (180 unused)
3: In set(loadProfiles, i = which(loadProfiles[[j]] >= loadProfiles[["maxICA"]]), :
Supplied 288 items to be assigned to 156 items of column 'load_ev_res_tou' (132 unused)
4: In set(loadProfiles, i = which(loadProfiles[[j]] >= loadProfiles[["maxICA"]]), :
Supplied 288 items to be assigned to 156 items of column 'load_ev_workplace' (132 unused)
我几乎被困在这一点上。任何指导将不胜感激。
【问题讨论】:
-
我发现github.com/Rdatatable/data.table/wiki/Getting-started 上的小插曲和文章非常有助于理解
data.table的好处。
标签: r data.table