I've loaded a table from a .CVS file using
mydata = read.csv("CS2Data.csv") # read csv file
which gave me:
mydata
Date DCM TMUS SKM RCI SPOK
1 11/2/2015 -0.88 -2.16 -1.04 1.12 0.67
2 12/1/2015 1.03 3.26 -2.25 -5.51 -0.23
3 1/4/2016 1.94 1.29 0.13 -1.16 0.11
4 2/1/2016 -0.41 -2.94 0.99 3.93 -0.19
5 3/1/2016 -0.68 1.27 -0.79 -2.06 -0.33
6 4/1/2016 1.82 1.22 -0.05 -1.27 -0.46
7 5/2/2016 -0.36 3.40 0.63 -2.77 0.46
8 6/1/2016 1.94 0.77 0.51 -0.26 1.66
9 7/1/2016 0.12 3.18 1.84 -1.34 -0.67
10 8/1/2016 -1.83 -0.20 -1.10 -0.90 -1.91
11 9/1/2016 0.05 0.31 1.11 0.80 1.17
12 10/3/2016 -0.02 3.19 -0.81 -4.00 0.29
I'd like to find all combination of any 3 of the 5 numbers for each month (row).
I tried using the combn
function based on an answer I found here:
combin <- combn(mydata, 3, rowSums, simplify = TRUE)
but that gave me the error-
"Error in FUN(x[a], ...) : 'x' must be numeric"
Next I tried naming each column separately
DCM=mydata[2]
TMUS=mydata[3]
SKM=mydata[4]
RCI=mydata[5]
SPOK=mydata[6]
and then using:
stock_ret <- data.table(DCM, TMUS,SKM,RCI,SPOK)
combin <- combn(stock_ret, 3, rowSums, simplify = TRUE)
I suspect there's an easier way to just use the column headers directly from the .CVS file to do this but I'm stuck.
Get all but the first column with dates (origin of the error in the question):
mydata <- mydata[,-1]
Use combn
to calculate selecting 3 columns at a time:
combn(mydata, m = 3, FUN = rowSums, simplify = TRUE)
Example:
> mydata <- iris[1:10,1:4]
> combn(mydata, m = 3, FUN = rowSums, simplify = TRUE)
[,1] [,2] [,3] [,4]
[1,] 10.0 8.8 6.7 5.1
[2,] 9.3 8.1 6.5 4.6
[3,] 9.2 8.1 6.2 4.7
[4,] 9.2 7.9 6.3 4.8
[5,] 10.0 8.8 6.6 5.2
[6,] 11.0 9.7 7.5 6.0
[7,] 9.4 8.3 6.3 5.1
[8,] 9.9 8.6 6.7 5.1
[9,] 8.7 7.5 6.0 4.5
[10,] 9.5 8.1 6.5 4.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With