Error in sum(x[i:(i + 50)], na.rm = TRUE) : invalid 'type' (character) of argument - sum

I am new in R , and I am trying to do a script to calculate the sliding mean of some data.
This is how my data looks like:
Timestamp Accelerometer X Accelerometer Y Accelerometer Z
1 121219.757080078 -5.66180946541818 8.85684119781125 1.65407075345669
2 121239.288330078 -7.38255951126451 9.4117333531527 1.44410517346543
it has around 6000 rows, and I need to calculate the mean of Accelerometer x, Accelerometer Y, and Accelerometer Z each fifty rows. So from the data of row 1 to 50 I must get the mean of the 3 variables, then from rows 51 to 100, and so on until row 6000.
I tried with (for the first variable):
library(reshape2)
library(reshape)
x <- deadlift$`Accelerometer X`
win.size <- 50
slide <- 50
results <- data.frame(index=numeric(),win.mean=numeric())
i<-1
j<-1
while (i<length(x)) {
win.mean<-sum(x[i:(i+50)],na.rm = TRUE)/win.size
results[j,]<-c(i,win.mean)
i<-i+slide
j<-j+1
}
but I get this message:
Error in sum(x[i:(i + 50)], na.rm = TRUE) :
invalid 'type' (character) of argument
any help?
Thank you.

Problem solved.
the problem was that the object x was created as character. I converted it to numeric with as.numeric.
It worked.
Regards,

Related

Z3 ArithRef type: is there a way to show value once model evaluated?

Using Z3Py, once a model has been checked for an optimization problem, is there a way to convert ArithRef expressions into values?
Such as
y = If(x > 5, 0, 0.5 * x)
Once values have been found for x, can I get the evaluated value for y, without having to calculate again based on the given values for x?
Many thanks.
You need to evaluate, but it can be done by the model for you automatically:
from z3 import *
x = Real('x')
y = If(x > 5, 0, 0.5 * x)
s = Solver()
r = s.check()
if r == sat:
m = s.model();
print("x =", m.eval(x, model_completion=True))
print("y =", m.eval(y, model_completion=True))
else:
print("Solver said:", r)
This prints:
x = 0
y = 0
Note that we used the parameter model_completion=True since there are no constraints to force x (and consequently y) to any value in this model. If you have sufficient constraints added, you wouldn't need that parameter. (Of course, having it does not hurt.)

How to insert new row after every 5 rows in Matlab?

I get time-domain measurement data from my oscilloscope (the data is an array of size 200000x2, the first column is for time and the second column is for the measurement). The sample time is 0.1 microseconds, but after every 5 rows, it changes to 0.2 microseconds. Now I'd like to perform an FFT analysis. I'll need to insert a new row every 5 rows to accomplish this.
Could someone please show me how to create a program that inserts a new row after every 5 rows and fills the rows with the average value of the adjacent rows in Matlab?
Say you have data like the following:
t = [0.0, 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9];
data = [t.', cos(t.')];
You can use interp1 to resample the data at regular intervals as follows:
dt = 0.1; % desired sampling rate
t = t(1):dt:t(end); % desired sample locations
y = interp1(data(:,1), data(:,2), t);
plot(t, y, 'o-');
I don't know if there is an easier way or if the below code is is correct for all sizes and shapes.
function [mtxnew] = interleavedcopying(mtx, n1, n2)
if(nargin == 0)
clc;
% input data which has 20 rows and 3 columns
mtx = rand(15, 1);
n1 = 5;
n2 = 6;
end
nn = size(mtx, 1);
% averaging currently works for single intermediate point only
assert(n2 == n1+1);
% this code works only for the "perfect" input case
assert(rem(nn, n1) == 0);
% make into groups of n1 rows
ii = floor([0 : nn-1]/n1)
% find the new locations where the data fits into
% nn/n1 is the reason why this code will work only for the "perfect" input
iinew = ii*n2 + repmat([1:n1], [1, nn/n1])
% create a big enough matrix filled with NaNs
nnnew = nn*n2/n1 -1;
mtxnew = NaN * zeros(nnnew, size(mtx, 2))
% copy the raw data
mtxnew(iinew, :) = mtx
% now fill in the avearge
kk = n2 : n2 : nnnew
mtxnew(kk, :) = ( mtxnew(kk-1, :) + mtxnew(kk+1, :) )/2;
plot(1:size(mtxnew, 1), mtxnew, '-x', kk, mtxnew(kk, :), 's');
end

Detect the "outliers"

In a column I have values like 0.7,0.85, 0.45, etc but also it might happen to have 2.13 which is different than the majority of the values. How can I spotted this "outliers"?
Thank you
Call scipy.stats.zscore(a) with a as a DataFrame to get a NumPy array containing the z-score of each value in a. Call numpy.abs(x) with x as the previous result to convert each element in x to its absolute value. Use the syntax (array < 3).all(axis=1) with array as the previous result to create a boolean array. Filter the original DataFrame with this result.
z_scores = stats.zscore(df)
abs_z_scores = np.abs(z_scores)
filtered_entries = (abs_z_scores < 3).all(axis=1)
new_df = df[filtered_entries]
You could get the standard deviation and mean of the set and remove anything more than X (say 2) standard deviations from the mean?
The following would calculate the standard deviation
public static double StdDev(this IEnumerable<double> values)
{
double ret = 0;
if (values.Count() > 1)
{
double avg = values.Average();
double sum = values.Sum(d => Math.Pow(d - avg, 2));
ret = Math.Sqrt((sum) / (values.Count() - 1));
}
return ret;
}

rjags error Invalid vector argument to ilogit

I'd like to compare a betareg regression vs. the same regression using rjags
library(betareg)
d = data.frame(p= sample(c(.1,.2,.3,.4),100, replace= TRUE),
id = seq(1,100,1))
# I am looking to reproduce this regression with jags
b=betareg(p ~ id, data= d,
link = c("logit"), link.phi = NULL, type = c("ML"))
summary(b)
Below I am trying to do the same regression with rjags
#install.packages("rjags")
library(rjags)
jags_str = "
model {
#model
y ~ dbeta(alpha, beta)
alpha <- mu * phi
beta <- (1-mu) * phi
logit(mu) <- a + b*id
#priors
a ~ dnorm(0, .5)
b ~ dnorm(0, .5)
t0 ~ dnorm(0, .5)
phi <- exp(t0)
}"
id = d$id
y = d$p
model <- jags.model(textConnection(jags_str),
data = list(y=y,id=id)
)
update(model, 10000, progress.bar="none"); # Burnin for 10000 samples
samp <- coda.samples(model,
variable.names=c("mu"),
n.iter=20000, progress.bar="none")
summary(samp)
plot(samp)
I get an error on this line
model <- jags.model(textConnection(jags_str),
data = list(y=y,id=id)
)
Error in jags.model(textConnection(jags_str), data = list(y = y, id = id)) :
RUNTIME ERROR:
Invalid vector argument to ilogit
Can you advise
(1) how to fix the error
(2) how to set priors for the beta regression
Thank you.
This error occurs because you have supplied the id vector to the scalar function logit. In Jags inverse link functions cannot be vectorized. To address this, you need to use a for loop to go through each element of id. To do this I would probably add an additional element to your data list that denotes how long id is.
d = data.frame(p= sample(c(.1,.2,.3,.4),100, replace= TRUE),
id = seq(1,100,1), len_id = length(seq(1,100,1)))
From there you just need to make a small edit to your jags code.
for(i in 1:(len_id)){
y[i] ~ dbeta(alpha[i], beta[i])
alpha[i] <- mu[i] * phi
beta[i] <- (1-mu[i]) * phi
logit(mu[i]) <- a + b*id[i]
}
However, if you track mu it is going to be a matrix that is 20000 (# of iterations) by 100 (length of id). You are likely more interested in the actual parameters (a, b, and phi).

How to set dimensions of LineSeries

I have a line series that covers data from 1 to 20 along the X axis and 0 to 1 along the Y axis. My problem is that the x axis always starts at 0 and goes to the furthest value and the Y axis starts at 0 but only goes to the furthest value as well. How can I set these dimensions?
So for the Y axis this is what you want
plotModel.Axes.Add(new LinearAxis()
{
Title = "Y axis Name",
Position = AxisPosition.Left,
MinorStep = 0.1,
FilterMinValue = -1,
FilterMaxValue = 1
});
As for the X axis it seems to be more annoying handLabeling seems to be the only way.
plotModel.Axes.Add(new CategoryAxis()
{
Title = "X axis name",
Position = AxisPosition.Bottom,
Labels = {"1","2","3","4","5","6" } // ... upto 20
});
Then every item you add index the value of the Category label.
For example if I want an column of 64 on 3 in X axis then the code would look like this:
var item =new ColumnItem(62, 2); // index 2 being value "3"