Question

Let's say I have 3 vectors (strings of 10):

X <- c(1,1,0,1,0, 1,1, 0, NA,NA)
H <- c(0,0,1,0,NA,1,NA,1, 1, 1 )
I <- c(0,0,0,0,0, 1,NA,NA,NA,1 )

Data.frame Y contains 10 columns and 6 rows:

1 2 3 4 5 6 7 8 9 10  
0 1 0 0 1 1 1 0 1  0      
1 1 1 0 1 0 1 0 0  0      
0 0 0 0 1 0 0 1 0  1      
1 0 1 1 0 1 1 1 0  0      
0 0 0 0 0 0 1 0 0  0      
1 1 0 1 0 0 0 0 1  1

I'd like to use vector X, H en I to make column selections in data.frame Y, using "1's" and "0's" in the vector as selection criterium . So the results for vector X using the '1' as selection criterium should be:

X <- c(1,1,0,1,0, 1,1, 0, NA,NA)
1 2   4    6 7
0 1   0    1 1
1 1   0    0 1
0 0   0    0 0
1 0   1    1 1
0 0   0    0 1
1 1   1    0 0

For vector H using the '1' as selection criterium:

H <- c(0,0,1,0,NA,1,NA,1, 1, 1 )
3      6    8  9  10
0      1    0  1  0
1      0    0  0  0
0      0    1  0  1
1      1    1  0  0
0      0    0  0  0
0      0    0  1  1

For vector I using the '1' as selection criterium:

I <- c(0,0,0,0,0, 1,NA,NA,NA,1 )
6          10
1          0
0          0
0          1
1          0
0          0
0          1

For convenience and speed I'd like to use a loop. It might be something like this:

all.ones <- lapply[,function(x) x %in% 1]

In the outcome (all.ones), the result for each vector should stay separate. For example:

X 1,2,4,6,7    
H 3,6,8,9,10
I 6,10
Was it helpful?

Solution

The standard way of doing this is using the %in% operator:

Y[, X %in% 1]

To do this for multiple vectors (assuming you want an AND operation):

mylist = list(X, H, I, D, E, K)
Y[, Reduce(`&`, lapply(mylist, function(x) x %in% 1))]

OTHER TIPS

The problem is the NA, use which to get round it. Consider the following:

x <- c(1,0,1,NA)
x[x==1]
[1]  1  1 NA
x[which(x==1)]
[1] 1 1

How about this?

idx <- which(X==1)
Y[,idx]

EDIT: For six vectors, do

idx <- which(X==1 & H==1 & I==1 & D==1 & E==1 & K==1)
Y[,idx]

Replace & with | if you want all columns of Y where at least one of the lists has a 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top