Help learning r

tyno

New Member
#1
Good Day all, i just joined this forum, it the help of learning R,and just a wbie to R,learning on my own.I understand how to do various plot now,reading data into r.i want to learn function in R.i have the below data i want to start with.

SN date company shareprice
1 10/15/2005 XYZ 2.1
2 10/18/2005 XYZ 3.1
3 11/19/2005 XYZ 4.1
4 11/21/2005 XYZ 2.0
5 12/09/2005 XYZ 5.9

please i want a function name price that will take one argument data and return shareprice for that day-i need a code for this,and if you dont mind an explanation of code
price<-(10/18/2005)

return :
price(3.1)
 
#2
Let the matrix object in R be called X.

Then to return the price at that date what you want is to type

Code:
X[which(X[,2]=="10/18/2005"),4]
Or a function:
Code:
price <- function(date="Insert character date object here",matrix){
    return( matrix[which(matrix[,2]==date),4] )
}
.

The ",4]" refers to the 4th column, the "which(X[,2]=="10/18/2005")" is asking R which element of the 2nd column of X is equal to that date (so, which row in X you need to navigate to/return).
 
Last edited:
#3
If you're doing a project with multiple stocks I strongly recommend translating this data into a format where the columns are individual stocks and the rows are dates that are shared by each stock. Put NAs in the spots where you don't have stock data and all econometric functions in R will automatically handle this by excluding rows. I do a lot of projects with stock data and I can tell you that you will be saving yourself a lot of heartache if you follow this advice.

Working with data stacked up like that is a nightmare.
 

tyno

New Member
#4
Thanks so much all for you time to help out,much appreciated.



Let the matrix object in R be called X.

Then to return the price at that date what you want is to type

Code:
X[which(X[,2]=="10/18/2005"),4]
Or a function:
Code:
price <- function(date="Insert character date object here",matrix){
    return( matrix[which(matrix[,2]==date),4] )
}
.

The ",4]" refers to the 4th column, the "which(X[,2]=="10/18/2005")" is asking R which element of the 2nd column of X is equal to that date (so, which row in X you need to navigate to/return).