Darwin PC
Darwin PC

Reputation: 931

How to get the values separated by a comma from a List?

I would like to complete some analysis, I have already extracted in a new List object (named "NAcol") the number of columns with NA values (because this columns do not let me run the cor.test() function).

ok, this is my List:

> NAcol
[[1]]
 [1]  38  45  52  55  56  57  58  59  60 
[10] 101 102 103 104 105 118 119 120 131 
[19] 134 136 137


>

then, I would like to use the numbers of this List separated by a comma to exclude the columns of my data.frame to run my correlation.

That is what I would like to have:

cor.test(mydata[,2], mydata[,-c(38, 45, 52, 55, 56, 57, 58, 59, 60, 
                               101, 102, 103, 104, 105, 118, 119, 120, 131, 
                               134, 136, 137 ] )

as you can see, I want to exclude all these columns, which are the numbers of my List "NAcol".

I don't know how or which function to use, I have tried the functions unlist() and split() without success.

I will appreciate very much your help.

Darwin

Upvotes: 0

Views: 230

Answers (1)

Peter Diakumis
Peter Diakumis

Reputation: 4032

The NAcol is a list containing one element which is an atomic vector. You can access this vector using the [[ function:

> NAcol <- list(1:10)
> NAcol
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

> NAcol[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

And then use it however you wish.

Edit: but cor.test only makes sense for numeric vectors of the same length. As Richard notes, from ?cor.test:

x, y: numeric vectors of data values. ‘x’ and ‘y’ must have the same length.

So instead of filtering out columns, you can filter out rows with NAs using the complete.cases function, or use the na.action parameter of cor.test - see here a similar question: How to compute a running cor.test() in a data.frame with NA values in R?. Then you can examine the correlation between pairs of columns with complete rows.

Upvotes: 2

Related Questions