let's say i have the following list :
pop = [5,4,3,4,2,5,1,6,7,6,10,13,5,8,8]
I then put them into a DataFrame, and for each row, append the value of the first column to a list. I then plot and frame the list to produce the animation :
df = DataFrame(pop, :auto)
a = Animation()
li = []
for i in df.x1
append!(li,i)
plt = plot(li, ylim=(0,20), xlim=(0,length(df.x1)))
frame(a, plt)
end
gif(a)
The frame rate for Animation object is too fast, i would like to slow it down, how do i do that?
the easy answer is gif(a, fps = whatever i want the frame rate to be)
Related
Im trying to expand the size of multidimensional array.
More particullary I have an 10x3x3 (rowsxcolumnsxmatrix) array and I want to expand it to become an 20x3x3 array.
I want to keep my current data in the first 10 rows and just resize their rows so I can add more data. Ideally the new rows should have 0s.
I can do this with loops but Im wondering if there is a function that can do the whole process automatically.
Thanks in advance
You can use the library abind.
library(abind)
v1=numeric(10)
v2=numeric(3)
a=array(c(v1, v2), dim = c(10, 3, 3))
res <- abind(originalArray, a, along = 1)
Here is my code right now:
f=function(Symbol, start, end, interval){
getSymbols(Symbols=Symbol, from=start, to= end)
Symbol=data.frame(Symbol)
a=length(Symbol$Symbol.Adjusted)
b=a/interval
c=ceiling(b)
origData=as.data.frame(matrix(`length<-`(Symbol$Symbol.Adjusted, c * interval), ncol = interval, byrow = TRUE))
return(origData)
}
f("SPY", "2012-01-01", "2013-12-31", 10)
Next I need to Get the adjusted close price and consider this price data only for following tasks. Split daily stock adjusted close price into N blocks as rows in a data frame. So that each block containing M days (columns) data, where M equals to the time interval value. It’s referred as origData in my code.
The function is supposed to return the data frame origData, but whenever I try running this it tells me that the Symbol data frame is empty. How do I need to change my function to get the data frame output?
#IRTFM's observations are correct. Incorporating those changes you can change your function to :
library(quantmod)
f = function(Symbol, start, end, interval){
getSymbols(Symbols=Symbol, from=start, to= end)
data= get(Symbol)
col = data[, paste0(Symbol, '.Adjusted')]
a=length(col)
b=a/interval
c=ceiling(b)
origData= as.data.frame(matrix(`length<-`(col, c * interval),
ncol = interval, byrow = TRUE))
return(origData)
}
f("SPY", "2012-01-01", "2013-12-31", 10)
I haven't figured out what the set of expressions inside the data.matrix call is supposed to do and you made no effort to explain your intent. However, your error occurs farther up the line. If you put in a debugging call to str(Symbol) you will see that Symbol will evaluate to "SPY" but that is just a character value and not an R object name. The object you wnat is named SPY and the way to retrieve an object's value when you can only have access to a character value is to use the R function get, So try adding this after the getSymbols call inside the function:
library(quantmod) # I'm assuming this was the package in use
...
Symbol=data.frame( get(Symbol) )
str(Symbol) # will print the result at your console
....
# then perhaps you can work on what you were trying inside the data.matrix call
You will also find that the name Symbol.Adjusted will not work (since R is not a macro language). You will need to do something like:
a=length( Symbol[[ paste0(Symbol, ".Adjusted")]] )
Oh wait. You overwrote the value for Symbol. That won't work. You need to use a different name for your dataframe. So why don't you edit your question to fix the errors I've identified so far and also describe what you are trying to do when you were using as.data.frame.
since I am fairly new to R I am struggling for days to come to the right solution. All the internet and stackoverflow search could not bring me ahead so far.
All tries with rbind, cbind, lapply, sapply did not work. So here is the problem:
I have a data frame given wich a time series in column "value X"
I want to calculate single and exponential moving averages on this column (SMA and EMA).
Since you can change the parameter "n" as window size in SMA/EMA calculation I want to change the parameter in a loop starting from 5 to 150 in steps of 5. And then write the result into a data frame.
So the data frame should look like.
SMA_5 | SMA_10 | SMA_15 .... EMA_5 | EMA_10 | EMA_15 ...
Ideally the column names are also created in this loop.
Can you help me out?
Thank you in advance
As far as I know, the loops are seen as a non-optimal solution in R and should be avoided if possible. It seems to me that in-built R functions sapply and colnames may provide quite a simple solution for your problem:
library("TTR")
# example of data
test <- data.frame(moments = 101:600, values = 1:500)
seq_of_windows_size <- seq(from = 5, to = 150, by = 5)
col_names_of_sma <- paste("SMA", seq_of_windows_size, sep = "_")
SMA_columns <- sapply(FUN = function(i) SMA(x = test$values, n = i),
X = seq_of_windows_size)
colnames(SMA_columns) <- col_names_of_sma
Then you'll have just to add the SMA_columns to your original dataframe. The steps for EMA may be much the same.
Hope, it helps :)
Here I have a function which I want to equalize the number of stops from a object in motion. To carry out this, there is a position list (in which this function is named Trip), and duration which is the length of trip but will be used in further development of the code.
Now to know the number of the stop throughout the trip what I have to do is for each Trip, which has different positions as:
x,y,z
10,11,13
12,11,14
13,11,15,
....
**20,11,35
20,11,35
20,11,35**
Compare themselves to know which are equal.
On this last positions as the object remain on the same location we can conclude was stopped. So, in order to know the stop we need to compare each position with the next ones.
I write this code:
StopsNumber <- function(Trip,Duration)
{
i=1
aux = Trip
while(i<length(Trip))
{
if(aux[i] == aux[i+1] && aux[i] == aux[i+2]){
Stop = aux[i]
NStops = Nstops+1
}
aux = [aux+1]
i=i+1
} # end
return (Stop,Nstops)
}
MThe problem I think is that i do not know how to create list of things. For instance: on Stop = aux[i] I don't know if it is working out properly. Because i want to do Stop be a list (or a vector, with aux, (those positions where the object has been quiet).And doing this if there are more than one stops, the last one will replace the rest.
May somebody help me?
Thank you
Your definitions of movement, intervals and stops are unclear. Therefore the code is fairly long to avoid misunderstandings. Otherwise it could be boiled down one or two lines. First some clear cut definitions
An interval is some time between between to xyz-points
Movement has occured in an interval, if start and end point differ in space
A stop is an interval of no movement after an interval of movement
You can choose to assume the object was(or was not) in movement before the first interval. Thus a stop can happen already in first interval.
a tip: try out the loop-functions apply(), sapply(), lapply() and foreach() instead of the low-level for() and while().
the code
#your data added some more positions
mixed.vector = c(
10,11,13,
12,11,14,
13,11,15,
20,11,35,
20,11,35, #this is a stop
20,11,35,
13,11,25,
10,20,30,
10,20,30) #this is a stop
#convert data to appropiate data structure.
#I suggest a matrix. List of vector would also do
#some tricks to convert (multiple ways to do this)
#mixed vector to matrix
xyz.matrix = matrix(mixed.vector,ncol=3,byrow=TRUE)
print(xyz.matrix) #each row is a position, columns are x, y and z respectively.
#matrix to list of vectors (if this structure is preferred)
list_of_vectors = split(xyz.matrix,1:dim(xyz.matrix)[1])
print(list_of_vectors)
#list of vectors to matrix (if this is how your data initially is ordered)
xyz.matrix = do.call(rbind,list_of_vectors)
print(xyz.matrix) #and we're back with a matrix
#function checking if intervals have no movement
#(total number of intervals is number of positions minus 1)
find_interval_with_movement = function(XYZ.m) {
nrows = dim(XYZ.m)[1] #scalar of n.position rows
interval_with_movement = !apply(XYZ.m[-nrows,]==XYZ.m[-1,],1,all) #check pairs of row if x y z match.
return(interval_with_movement)
}
#function finding stops, optional assuming the object was moving before first interval
find_stops = function(interval_movements,object.moving.at.t0=TRUE) {
intervals_to_search= c(object.moving.at.t0,interval_movements)
len = length(intervals_to_search)
#search for intervals with no movement where previous interval has movement
did.stop = sapply(2:len,function(i) all(intervals_to_search[(i-1):i] == c(T,F)))
return(did.stop)
}
#these intervals has no movement
print(!find_interval_with_movement(xyz.matrix))
#these intervals had no movement, where previous had
print(find_stops(find_interval_with_movement(xyz.matrix)))
#and the full number of stops
print(sum(find_stops(find_interval_with_movement(xyz.matrix))))
I am using some R code that uses a data table class, instead of a data frame class.
How would I do the following operation in R without having to transform map.dt to a map.df?
map.dt = data.table(chr = c("chr1","chr1","chr1","chr2"), ref = c(1,0,3200,3641), pat = c(1,3020,3022, 3642), mat = c(1,0,3021,0))
parent = "mat"
chrom = "chr1"
map.df<-as.data.frame(map.dt);
parent.block.starts<-map.df[map.df$chr == chrom & map.df[,parent] > 0,parent];
Note: parent needs to be dynamically allocated, its an input from the user. In this example I chose "mat" but it could be any of the columns.
Note1: parent.block.starts should be a vector of integers.
Note2: map.dt is a data table where the column names are c("chr","ref","pat","mat").
The problem is that in data tables I cannot access a given column by name, or at least I couldn't figure out how.
Please let me know if you have some suggestions!
Thanks!
It's a little unclear what the end goal is here, especially without sample data, but if you want to access rows by character name there are two ways to do this:
Columns = c("A", "B")
# .. means "look up one level"
dt[,..Columns]
dt[,get("A")]
dt[,list(get("A"), get("B"))]
But if you find yourself needing to use this technique often, you're probably using data.table poorly.
EDIT
Based on your edit, this line will return the same result, without having to do any as.data.frame conversion:
> map.dt[chr==chrom & get(parent) > 0, get(parent)]