我有两列这样的值:
>bb
GDis BDis
1 12.291488 8.009909
2 11.283319 13.625103
3 6.674549 8.629232
4 13.493121 17.175888
5 9.550731 9.867878
6 9.193895 9.785301
7 10.541702 10.941371
8 9.849527 9.496284
9 8.682287 8.133774
10 8.439381 4.335260
我需要添加额外的列并将其称为Index
,如果GDis/BDis
更大,则会计算比率GDis
,如果BDis/GDis
更大,则会BDis
。< / p>
我该怎么做?
答案 0 :(得分:7)
您可以使用pmax
和pmin
。
transform(bb, Index = pmax(GDis, BDis) / pmin(GDis, BDis))
你也可以使用算术:
transform(bb, Index = (GDis / BDis) ^ (1 - 2 * (BDis > GDis)))
结果:
GDis BDis Index
1 12.291488 8.009909 1.534535
2 11.283319 13.625103 1.207544
3 6.674549 8.629232 1.292856
4 13.493121 17.175888 1.272937
5 9.550731 9.867878 1.033207
6 9.193895 9.785301 1.064326
7 10.541702 10.941371 1.037913
8 9.849527 9.496284 1.037198
9 8.682287 8.133774 1.067436
10 8.439381 4.335260 1.946684
答案 1 :(得分:5)
尝试
transform(bb, Index=ifelse(GDis>BDis, GDis/BDis, BDis/GDis))
# GDis BDis adn
#1 12.291488 8.009909 1.534535
#2 11.283319 13.625103 1.207544
#3 6.674549 8.629232 1.292856
#4 13.493121 17.175888 1.272937
#5 9.550731 9.867878 1.033207
#6 9.193895 9.785301 1.064326
#7 10.541702 10.941371 1.037913
#8 9.849527 9.496284 1.037198
#9 8.682287 8.133774 1.067436
#10 8.439381 4.335260 1.946684
答案 2 :(得分:3)
不如其他答案那么好但是怎么样?
bb$RATIO=ifelse(bb$GDis>bb$BDis,bb$GDis/bb$BDis,bb$X1/bb$GDis)