Double If else condition - r

I have
sb_bs <- structure(c(1.12091846661435, 1.18009738415273, 1.11298146308129, 1.01543479350125, 1, 0.951241085342297, 1.13080707303053,
1.02485190419514, 1.1642497054576,
1.09758768260489, 1.03143204936253,
0.962263806546468, 1.13646386224131,
1.05528801854607, 1, 1.0099677412001, 1.27733703174185, 1.08617651501537, 1.09642463008668, 0.962776610165752, 1.09650777274647, 1.02585985559578, 1, 0.999386657988493, 1.13956770512708,
1.02801721288972, 1.08668114989057, 1.00619821265949, 1.18651806206661, 1.10567560388514, 1.13871340983327, 1.0641141127524, 1.14138250428664, 1.07165852394532, 1.14672434661463, 1.05773939982737, 1.03068291407157, 0.969220946334891, 1, 0.996545720184137, 1.16201672634516, 1.14932701076931, 1.03239099834277, 0.952596628890447, 1.1015668980208, 1.01070602087167, 1.06446487490351, 0.951035926316207, 1.123214561944, 1.02175192620079, 1.05854401298598, 0.955952082548675, 0.93666054698966, 0.78951026731046, 1.07778659045028, 1.00399655566558, 1.17991276258629, 1.08980598472291, 1, 0.988417315255171,
1.17162519954207, 1.08543591629641, 1.16332270621974, 1.04640496770377,
1.07628139834293, 0.660300975816023, 1.18023510375109, 1.06381322815647, 1, 0.985519330082672, 1, 1, 1.11167375547688, 0.989782753394904, 1.19539027283808, 1.08094458111008, 1.08360592510174, 0.995189438996505, 1.12905282067727, 1.01854704758263, 1, 0.999513001091598, 1.12582107084784,
1.03809878502361, 1.20383394437524, 1.11282621100709, 1.11890798835696,
1.02069677382081, 1.1718663965017, 1.14932701076931, 1.10567893629417,
1.01280861843888, 1, 0.997229184135707, 1.36291711157704, 1.21997211505057, 1, 0.995717127378999,
1.11925862571016, 1.0265000455924, 1.19813504773696, 1.08093802496861, 1.09083155239671, 1.00733022178486, 1.08576682175743, 1.02765522155381, 1.14435310285118, 1.0368424021034, 1.10728085614489, 1.03369127812722, 1, 1, 1, 1.0010343593862, 1.09869128313384, 1.00986110345981, 1.16569766816216, 1.06809300727111, 1.08691881875315, 0.987756631843919, 1, 0.995593919635795, 1.21060416986701, 1.11431887118973, 1.17372870338765, 1.08555976717623, 1.12767749680449,
1.05498213441735, 1.20877696937163, 1.13951692732442, 1.20557208134671,
1.10161115189349, 1.14075335025544, 0.986457883171349, 1.10161115189349,
1.01901529496121, 1, 1.00246940215672, 1.09886441422695, 0.991136014242189, 1.13353139262452, 0.999202603818596, 1.25545764969252, 1.16709504376582, 1.253813300474, 1.18586034201829, 1.36139434951718, 1.27643122050034, 1.11532774927192, 1.0249592726384, 1, 0.98818636452525, 1.11734646265344, 1.0291275567626, 1.09096560662508,
0.995745426192434, 1, 1, 1.10951296399544, 1.01652115456415, 1.16550460579752, 1.11388837421179, 1, 0.997573772176866, 1, 0.98464674069702, 1, 0.997250277028562, 1, 1, 1, 0.999386657988493,
1.12580323330241, 1.0397394609463, 1, 0.999386657988493, 1, 0.997353796391289, 1.14155615975893, 1.05795767043203, 1, 0.972953439553992, 1, 1.00392875483313, 1, 0.995937255059779, 1, 1.00106654711201, 1.08073289044227, 1.02175192620079), .Dim = c(2L, 95L))
and I want run this if-else condition
if ((sb_bs[1,] == 1) || (sb_bs[2,] == 1)) {
rev_sell_buy <- 0
} else {
rev_sell_buy <- sb_bs[1,] - sb_bs[2,]
}
but it considers only the second condition (sb_bs[2,] == 1) in the result.
I need that if the value in the first or in the second row is 1, it return me 0. Else the difference sb_bs[1,] -(sb_bs[2,]).
How can I do that?

Try this
rev_sell_buy <- apply(sb_bs , 2 ,
function(x) if((x[[1]] == 1) | (x[[2]] == 1)) 0 else x[[1]] - x[[2]])

You do not really need any if-else, but could do:
rev_sell_buy <- sb_bs[1,] - sb_bs[2,]
rev_sell_buy[(sb_bs[1,] == 1) | (sb_bs[2,] == 1)] <- 0
Beware of the difference between | and || (see e.g. What is the difference between || and | in R ?)

Related

How to create custom hover tool with value mapping

I am trying to create a custom hover tool using which takes the y-value of the plot and maps the value to different value.
The code I could come up with so far to achieve this functionality is
from bokeh.models import HoverTool
import holoviews as hv
df = pd.DataFrame(
{
"zero": [0, 0, 0, 0, 0, 0, 0],
"one": [1, 1, 1, 1, 1, 1, 1],
"two": [2, 2, 2, 2, 2, 2, 2],
}
)
mapping = {i: c for i, c in enumerate(df.columns)}
def col_mapping(num):
return mapping[int(num)]
hover = HoverTool(tooltips=[("x", "$x"), ("y", "$y")])
img = hv.Image((df.index, np.arange(df.shape[1]), df.T)).opts(tools=[hover])
img
x and y will be float values. So the idea is to map the y coordinates to its corresponding value in the mapping dictionary
Let me know how I can get a new value in the hover tool so that when the value is b/w 0 and 1 it will be
Thanks
Here's how I'd do it:
code = f"return ({json.dumps(mapping)})[Math.floor(special_vars.y)];"
hover = HoverTool(tooltips=[("x", "$x"), ("y", "$y"), ('mapped_y', '$y{0}')],
formatters={'$y': CustomJSHover(code=code)})
If you need a some more complicated code than that of col_mapping, then you'd have to use a ColumnDataSource and just add to it the fully transformed column.

How I want to delete array values other than integers

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
for items in messy_list:
if items.isdigit() == 0:
messy_list.remove(items)
Please help me to do so?
You can do something like this (not in-place):
lst = [item for item in messy_list if isinstance(item, int) and not isinstance(item, bool)]

ControlsFX SpreadsheetView rowspan IndexOutOfBoundsException

I am new to JavaFX and ControlsFX.
I am trying to create a very basic SpreadsheetView using the ControlsFX library. Following is the function to populate and create the SpreadsheetView:
private fun spreadSheetFunc() : SpreadsheetView {
val rowCount = 15
val columnCount = 10
val grid = GridBase(rowCount, columnCount)
val rows = FXCollections.observableArrayList<ObservableList<SpreadsheetCell>>()
var list = FXCollections.observableArrayList<SpreadsheetCell>()
list.add(SpreadsheetCellType.STRING.createCell(0, 0, 1, 1, "row0-col0"))
list.add(SpreadsheetCellType.STRING.createCell(0, 1, 2, 1, "row0-col1"))
list.add(SpreadsheetCellType.STRING.createCell(0, 2, 1, 1, "row0-col2"))
rows.add(list)
list = FXCollections.observableArrayList()
list.add(SpreadsheetCellType.STRING.createCell(1, 0, 1, 1, "row1-col0"))
//commenting row1-col1 as row0-col1 has a rowspan of 2
//list.add(SpreadsheetCellType.STRING.createCell(1, 1, 1, 1, "row1-col1"))
list.add(SpreadsheetCellType.STRING.createCell(1, 2, 1, 1, "row1-col2"))
rows.add(list)
list = FXCollections.observableArrayList()
list.add(SpreadsheetCellType.STRING.createCell(2, 0, 1, 1, "row2-col0"))
list.add(SpreadsheetCellType.STRING.createCell(2, 1, 1, 1, "row2-col1"))
list.add(SpreadsheetCellType.STRING.createCell(2, 2, 1, 1, "row2-col2"))
rows.add(list)
list = FXCollections.observableArrayList()
list.add(SpreadsheetCellType.STRING.createCell(3, 0, 1, 1, "row3-col0"))
list.add(SpreadsheetCellType.STRING.createCell(3, 1, 1, 1, "row3-col1"))
list.add(SpreadsheetCellType.STRING.createCell(3, 2, 1, 1, "row3-col2"))
rows.add(list)
grid.setRows(rows)
return SpreadsheetView(grid)
}
On running it, I get the following error:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at
java.util.ArrayList.rangeCheck(ArrayList.java:653)
I know its happening because I am not adding any value for rowIndex=1 colIndex=1 (see the commented out line) ... but that is what I want.
The row0-col1 has a rowspan of 2 which should mean that even if my row1-col1 is absent, there shouldn't be any problem.
Why doesn't ControlsFX automatically take care of this?
If I uncomment that line, I get the following output:
Edit 1:
Also, I found another issue, when a colspan/rowspan occupies the whole column/row in the SpreadsheetView and then when one presses arrow key to navigate to cells you get an error:
The above situation arises when you press the right arrow key (Even though their isn't a cell on the right)
Let me apologize because it is not well documented how span must be made in the SpreadsheetView. I will update the documentation.
If you want to span, you have to put the same cell in every cell inside the span.
So either you build your own cell, and then in every place. In your case, you would add the same cell in row 0 column 1 and in row 1 column 1.
Or you could keep your code, and simply call the method spanRow on the Grid. This method will automatically take your cell and place it accordingly.
Regarding the second issue, please submit it to our issue tracker so we can fix it : https://bitbucket.org/controlsfx/controlsfx/issues?status=new&status=open
If you have other issue regarding the SpreadsheetView, consider posting in our Google group where we will get notifications : http://groups.controlsfx.org

Iterating over function and get each result value

I created the following function to determine the lag of two variables.
However, this function takes only two parameters, and I would like to run it over my whole dataset:
datSel <- structure(list(stat.resProp.Dwell.4 = c(0.000887705, 0.007954085,
-0.025859667, 0.024097552, 0.114052787, 0.023329207, 0.042143181,
-0.092587287, -0.004050228, -0.001624696, 0.020121403, -0.100502922,
0.057354185, 0.025463388, 0.037409854, 0.001561281, -0.028482938,
-0.004827041, 0.014411779, -0.029034298, 0.021053409, -0.067963182,
0.032070259, -0.038091783, 0.039751534, 0.027802281, -0.027802281,
-0.013355791, 0.009201236, -0.073403679, 0.021277398, -0.033901552,
0.012624153, -0.065733979, 0.032017801, -0.072042665, 0.041936911,
0.002861232, 0.017933468, -0.01698154, 0.006638242, -0.08375153,
-0.007220248, 0.0255507, 0.019980685, 0.013752673, 0.026000502,
-0.021134312, -0.019608471, 0.0166916, -0.021654389, 0.066402455,
0.024828862, -0.083302632, 0.042518482, -0.052439198, 0.037186281,
-0.056311172, -0.012270093), stat.lohn = c(0, -0.007558004, -0.015289567,
0, 0, -0.009609384, -0.019500305, 0, 0, -0.012458015, -0.025391532,
-0.000983501, 0, -0.00165265, -0.003313516, 0.000204576, 0, -0.004898564,
-0.009869709, 0, 0, -0.010574012, -0.021489482, 0, 0, -0.011534651,
-0.023476287, 0, 0, -0.00814845, -0.016498838, 0, 0, -0.0099856,
-0.020275409, -0.002818337, 0, -0.007212389, -0.014582736, 0,
0, -0.004121565, -0.008294445, 0, 0, -0.010766386, -0.021886884,
0, 0, -0.010179741, -0.02067574, 0, 0, -0.011797067, -0.024020039,
-0.002017983, -0.007343864, -0.007398196, -0.014962644), stat.resProp.Dwell.1 = c(0.012777325,
-0.002991775, -0.057819571, -0.00796817, -0.019386714, 0, 0.009740337,
0.005638356, -0.035148694, 0, 0.027084134, -0.160377856, 0.101169235,
-0.043007944, 0.043007944, -0.002580647, -0.015625318, 0.023347364,
0.007662873, -0.09607383, -0.024575906, 0.056733018, -0.000904568,
-0.058703392, 0.011450507, 0.007561473, 0.037879817, -0.032246,
0.042169401, -0.001796946, -0.024580209, -0.148788737, 0.082097362,
-0.000985707, -0.00098668, 0.003940892, -0.049380309, 0.005151995,
0.027371197, -0.025317808, 0.019299736, -0.047382704, -0.010604553,
0.082827084, -0.04516573, 0.003075348, 0.007139245, 0.022111454,
-0.004982571, -0.038701368, 0.018519048, -0.049096021, 0.061254226,
-0.020346582, 0.023363175, -0.00402415, -0.014213437, 0.023245109,
0.027587957), stat.carReg = c(0.022775414, 0.008073857, 0.002624717,
0.169431097, -0.144595366, 0.066716837, -0.086971929, 0.037928208,
0.071752161, -0.046824102, 0.106085873, 0.049965928, -0.057984255,
-0.091650262, 0.090732857, -0.082282389, 0.053376121, -0.044203971,
-0.022855425, 0.025856271, 0.000136493, 0.05579193, -0.293966656,
0.013645739, 0.059732986, 0.187020956, -0.145234848, 0.11041385,
-0.126539687, -0.000949877, 0.031473389, 0.020267816, -0.02180532,
-0.07175183, 0.147500145, -0.040559138, 0.008394819, 0.049045337,
-0.043050615, 0.094358754, -0.058408438, -0.005018402, -0.061717889,
0.100150837, -0.071100417, -0.084393865, 0.002854733, 0.002141389,
-0.026538398, 0.013480513, -0.046002189, -0.030495611, 0.052899746,
0.012842017, 0.064086498, 0.020757573, -0.043441298, -0.009563043,
0.048033848)), .Names = c("stat.resProp.Dwell.4", "stat.lohn",
"stat.resProp.Dwell.1", "stat.carReg"), row.names = c(NA, -59L
), class = "data.frame")
The function and my function call is:
select.lags<-function(x,y,max.lag=8) {
y<-as.numeric(y)
y.lag<-embed(y,max.lag+1)[,-1,drop=FALSE]
x.lag<-embed(x,max.lag+1)[,-1,drop=FALSE]
t<-tail(seq_along(y),nrow(y.lag))
ms=lapply(1:max.lag,function(i) lm(y[t]~y.lag[,1:i]+x.lag[,1:i]))
pvals<-mapply(function(i) anova(ms[[i]],ms[[i-1]])[2,"Pr(>F)"],max.lag:2)
ind<-which(pvals<0.05)[1]
ftest<-ifelse(is.na(ind),1,max.lag-ind+1)
aic<-as.numeric(lapply(ms,AIC))
bic<-as.numeric(lapply(ms,BIC))
structure(list(ic=cbind(aic=aic,bic=bic),pvals=pvals,
selection=list(aic=which.min(aic),bic=which.min(bic),ftest=ftest)))
}
for (i in length(datSel) ) {
for (y in length(datSel) ) {
d1<-ts(datSel[i])
d2<-ts(datSel[y])
lag <- select.lags(d1,d2,5)
}
}
As output of lag I get:
> lag
$ic
aic bic
[1,] -115.3623 -109.56679
[2,] -114.3370 -106.60972
[3,] -116.2026 -106.54350
[4,] -114.7030 -103.11210
[5,] -112.7153 -99.19253
[6,] -110.8018 -95.34721
[7,] -110.0812 -92.69477
[8,] -110.1427 -90.82446
$pvals
[1] 0.1952302 0.3017934 0.7858944 0.9176337 0.5040079 0.0604511 0.3406657
$selection
$selection$aic
[1] 3
$selection$bic
[1] 1
$selection$ftest
[1] 1
As you can see I get only 8 results back, however, my data.frame has 20 variables.
Any recommendation what I am doing wrong?
I appreciate your replies!
If you want to e.g. store the result of the AIC criterion:
lag.aic.store = matrix(NA, 4, 4)
for (i in 1:length(datSel) ) {
for (y in 1:length(datSel) ) {
d1<-ts(datSel[,i])
d2<-ts(datSel[,y])
lag <- select.lags(d1,d2,5)
lag.store.aic[i,y] = lag$selection$aic
}
}
You get 8 values in $ic because max.lag is 8, it has nothing to do with your number of variables.
Please also note that i added commas when indexing by variable for clarity and that you have to loop through 1:length(datSel) as otherwise you will only catch the last variable.

Get same output as R console in Java using JRI

When I enter the following commands directly into the R console
library("xts")
mySeries <- xts(c(1.0, 2.0, 3.0, 5.0, 6.0), order.by=c(ISOdatetime(2001, 1, 1, 0, 0, 0), ISOdatetime(2001, 1, 2, 0, 0, 0), ISOdatetime(2001, 1, 3, 0, 0, 0), ISOdatetime(2001, 1, 4, 0, 0, 0), ISOdatetime(2001, 1, 5, 0, 0, 0)))
resultingSeries <- to.monthly(mySeries)
resultingSeries
I will get an output like this
mySeries.Open mySeries.High mySeries.Low mySeries.Close
Jan 2001 1 6 1 6
When I look into the attributes, I see the following output
attributes(resultingSeries)
$dim
[1] 1 4
$dimnames
$dimnames[[1]]
NULL
$dimnames[[2]]
[1] "mySeries.Open" "mySeries.High" "mySeries.Low" "mySeries.Close"
$index
[1] 978307200
attr(,"tclass")
[1] "yearmon"
$tclass
[1] "POSIXct" "POSIXt"
$tzone
[1] ""
$class
[1] "xts" "zoo"
$.indexCLASS
[1] "yearmon"
This is the same I get in Java. I'm wondering where the magic happens so that I see the nice output I get in R. I have no access to the event loop, since I'm using JRI like this (since, it's the recommended way and simplifies error handling):
REngine engine = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine");
REXP result = engine.parseAndEval(...)
/edit
In Java I execute each command from above as follows:
REXP result = engine.parseAndEval("resultingSeries") // or any other command
What I get is
org.rosuda.REngine.REXPDouble#4ac66122+[12]
The payload being doubles: 1, 6, 1, 6
The attributes are the same as specified above.
Now R does some magic to display the output above. Is there a way I can get the same output without having to create it manually by myself? Where's the implementation stored, that R gets the above mentioned output?
Here is a piece of code that will work, here i extracted the first element of the field mySeries.Open from the object resultingSeries (which i converted to a data frame) which is equal to 1, notice that you can't pass all of the resultingSeries object strait into Java, you will need to break it down.
package stackoverflow;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;
/**
*
* #author yschellekens
*/
public class StackOverflow {
public static void main(String[] args) throws Exception {
String[] Rargs = {"--vanilla"};
Rengine rengine = new Rengine( Rargs, false, null);
rengine.eval("library('xts')");
rengine.eval("mySeries <- xts(c(1.0, 2.0, 3.0, 5.0, 6.0), order.by=c(ISOdatetime(2001, 1, 1, 0, 0, 0), ISOdatetime(2001, 1, 2, 0, 0, 0), ISOdatetime(2001, 1, 3, 0, 0, 0), ISOdatetime(2001, 1, 4, 0, 0, 0), ISOdatetime(2001, 1, 5, 0, 0, 0)))");
rengine.eval("resultingSeries <- to.monthly(mySeries)");
rengine.eval("resultingSeries<-as.data.frame(resultingSeries)");
REXP result= rengine.eval("resultingSeries$mySeries.Open");
System.out.println("Greeting from R: "+result.asDouble());
}
}
And the Java output:
run:
Greeting from R: 1.0
I figured out the following workaround. The solution is far from perfect.
R offers a command to save its console output as characters vector.
capture.output( {command} )
We can access the output using
REXPString s = rengine.parseAndEval("capture.output( to.monthly(mySeries))")
String[] output = result.asStrings()
The variable output will contain all output lines
[0] mySeries.Open mySeries.High mySeries.Low mySeries.Close
[1]Jan 2001 1 6 1 6
Alternatively you coud use JRIEngine and attack yourself to the event loop, which it did not want in my case (due to the more complicated error handling).

Resources