Pulling elements from one list to another under a criterion in R

4

The vector below indicates the regressions that I have circled.

regression_pairs=c("A~B", "C~D", "E~F", "G~H","I~J","K~L","M~N","O~P","Q~R")

regression_pairs

Below is the list where I saved the remainders of each regression residuals.new :

    residuals.new <- list()
     a=c(1,2,3,4,5)
 b=c(6,7,8,9,10)
 c=c(11,12,13,14,15)
 d=c(16, 17, 18, 19, 20)
 e=c(21,22,23,24,25)
 f=c(26,27,28,29,30)
 g=c(31,32,33,34,35)
 h=c(36,37,38,39,40)
 i=c(41,42,43,44,45)

 residuals.new[[1]]=a
 residuals.new[[2]]=b
 residuals.new[[3]]=c
 residuals.new[[4]]=d
 residuals.new[[5]]=e
residuals.new[[6]]=f
residuals.new[[7]]=g
residuals.new[[8]]=h
residuals.new[[9]]=i

residuals.new

That is, the residuals of the A~B regression are 1,2,3,4,5 , the residuals of the regression C ~ D are 6,7,8,9,10 and so on.

After a certain criterion I saw that the best pairs are represented by the list below:

bestresults<-list()

best_pairs=c("A~B", "G~H", "Q~R")

Now I need to figure out a way to create a list that takes the residuals related to the regressions presented by the best_pairs list.

Could someone help me?

Below is the result I'm looking for:

the.bestresiduals<-list()

 the.bestresiduals[[1]]=c(1,2,3,4,5)
 the.bestresiduals[[2]]=c(16, 17, 18, 19, 20)
 the.bestresiduals[[3]]=c(41,42,43,44,45)

the.bestresiduals

    [[1]]
    [1] 1 2 3 4 5

    [[2]]
    [1] 16 17 18 19 20

    [[3]]
    [1] 41 42 43 44 45

Any help?

    
asked by anonymous 22.08.2018 / 01:42

2 answers

4

You can use the match function to return the position of the best_pairs elements in the regression_pairs

regression_pairs=c("A~B", "C~D", "E~F", "G~H","I~J","K~L","M~N","O~P","Q~R")

residuals.new <- list(
                        a=c(1,2,3,4,5),
                        b=c(6,7,8,9,10),
                        c=c(11,12,13,14,15),
                        d=c(16, 17, 18, 19, 20),
                        e=c(21,22,23,24,25),
                        f=c(26,27,28,29,30),
                        g=c(31,32,33,34,35),
                        h=c(36,37,38,39,40),
                        i=c(41,42,43,44,45)
                      )

best_pairs=c("A~B", "G~H", "Q~R")

residuals.new[c(match(best_pairs, regression_pairs))]
#$a
#[1] 1 2 3 4 5

#$d
#[1] 16 17 18 19 20

#$i
#[1] 41 42 43 44 45
    
22.08.2018 / 02:33
2

Use the %in% function. If it is used as

x %in% y

it crosses x with y . It returns a vector of the size of x , informing the index in% with% of the y elements. In practice, see what happens in your problem:

regression_pairs %in% best_pairs
TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE

If I save this result to a vector called x , what I get is

indices <- regression_pairs %in% best_pairs
residuals.new[indices]

[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 16 17 18 19 20

[[3]]
[1] 41 42 43 44 45

More information can be found in the function help: indices (yes, ?match is equivalent to match , do not worry).

    
22.08.2018 / 02:32