Yannick Schwarz Yannick Schwarz - 7 months ago 93
R Question

Error: requires numeric/complex matrix/vector arguments when using matrix times vector multiplication

This is my code:

indices <- as.matrix(sapply(cpi_calc[2:nrow(cpi_calc), 1:ncol(cpi_calc)], as.numeric))
weigths <- as.matrix(sapply(cpi_calc[1, 1:ncol(cpi_calc)], as.numeric))
CPI77_82 <- indices %*% weights


I want to calculate a CPI with a index matrix and a weights vector. Both matrix and vector appear as num in the variable window. I have no clue why the heck the matrix multiplication doesn't work.

Error in indices %*% weights :
requires numeric/complex matrix/vector arguments


And I know there are a lot of other similar questions out there, but my code seems fine for me and I tried all the answers to other similar questions. please help! :)

Edit:

> cpi_calc[2:6, 1:6]
# A tibble: 5 x 6
X__1 X__2 X__3 X__4 X__5 X__6
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 100.00 100.00 100.00 100.00 100.00 100.00
2 99.99 100.00 100.07 100.01 100.80 101.59
3 99.52 99.58 99.94 100.01 101.03 101.38
4 99.46 99.44 99.85 100.01 101.03 101.03
5 99.13 99.37 99.79 99.97 101.00 101.82

> t(cpi_calc[1, 1:6])
[,1]
X__1 0.358
X__2 0.359
X__3 0.060
X__4 0.419
X__5 0.191
X__6 0.296

Answer Source

This works fine. You must have some NAs in your cpi_calc table. Try na.omit(cpi_calc)

cpi_calc <- read.table(text="0.358  0.359   0.06    0.419   0.191   0.296
100 100 100 100 100 100
99.99   100 100.07  100.01  100.8   101.59
99.52   99.58   99.94   100.01  101.03  101.38
99.46   99.44   99.85   100.01  101.03  101.03
99.13   99.37   99.79   99.97   101 101.82",header=FALSE)

as.matrix(cpi_calc[2:6, 1:6]) %*% t(cpi_calc[1, 1:6])
         1
2 168.3000
3 168.9282
4 168.5832
5 168.4024
6 168.4669
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download