Incorrect error of dimension:Correlation matrix

Hi All
i am trying to do a correlation matrix forbur first subset the variables to numeric variables only. I did that with this code
d4<-which(sapply(d3, is.numeric))
is.numeric(d4)
How ever when i am trying to create a new data for the correlation, i get this error
i have checked all my syntax and don't seem to know where i am going wrong
Please help!

d5<d4[,c('SW','MOI','YOI','DOI_CMC','RMOB','RYOB','RDOB_CMC','RCA','Region','TPR','DPR','NV','HEL','Has_Radio','Has_TV','Religion','WI','MOFB','YOB','DOB_CMC','DOFB_CMC','AOR','MTFBI','DSOUOM_CMC','RW','RH','RBMI')]
cor(d5)
library(Hmisc)
rcorr(as.matrix(d4))

ERROR MESSAGE

d5<-d4[,c('SW','MOI','YOI','DOI_CMC','RMOB','RYOB','RDOB_CMC','RCA','Region','TPR','DPR','NV','HEL','Has_Radio','Has_TV','Religion','WI','MOFB','YOB','DOB_CMC','DOFB_CMC','AOR','MTFBI','DSOUOM_CMC','RW','RH','RBMI')]
Error in d4[, c("SW", "MOI", "YOI", "DOI_CMC", "RMOB", "RYOB", "RDOB_CMC", :
incorrect number of dimensions
cor(d5)
SBP WT CSBP CWT
SBP 1.0000000 0.3768497 0.7119719 0.3260822
WT 0.3768497 1.0000000 0.2667614 0.8312830
CSBP 0.7119719 0.2667614 1.0000000 0.1988989

Can you provide a sample of how your d3 looks like - ideally all columns and a couple of rows. As far as I can see d4<-which(sapply(d3, is.numeric)) will result in a vector (1-dimensional), not a matrix or data.frame, so you cannot index it like d4[, ...] since that implies 2 dimensions.

Thanks so much for getting back
image
Please see attached view of the d3 data
how do i then select the numeric values in the two dimensional format(matrix) ?

Maybe this example with the iris data frame can help - I would recommend using select_if:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
iris_numeric <- iris %>%
    select_if(is.numeric)

head(iris_numeric)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1          5.1         3.5          1.4         0.2
#> 2          4.9         3.0          1.4         0.2
#> 3          4.7         3.2          1.3         0.2
#> 4          4.6         3.1          1.5         0.2
#> 5          5.0         3.6          1.4         0.2
#> 6          5.4         3.9          1.7         0.4

Created on 2020-02-09 by the reprex package (v0.3.0)

It worked!!! Thank you so much!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.