Search code examples
rcontainsnames

Check if vector have same names in a list of names and keep only the names that verify the condition in my vector


I have a list of letters called liste, and a vector called myvec, a dataframe and another vector ind1 as follow

###############
## my sample ##
###############
liste=LETTERS[seq( from = 1, to = 10 )]
df1=data.frame(ID1=seq(from=1,to=3,by=1),
               A=c(rep(1,3)),
               B=c(rep(2,3)),
               D=c(rep(3,3)),
               F=c(rep(4,3)),
               G=c(rep(5,3)))
myvec=c("A","B","G")
ind1=c(1,2,2,3,5,6)
names(ind1)=c("ID2","A","B","C","D","G")

ind1
ID2   A   B   C   D   G 
  1   2   2   3   5   6 

df1
  ID1 A B D F G
1   1 1 2 3 4 5
2   2 1 2 3 4 5
3   3 1 2 3 4 5

 liste
 "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

What i want to do is (i figured it out the 3 first checks while writing the post but not the last):

1- check if names of df1 are in myvec : for my example it will give TRUE because of A B G.

2- check if myvec is contained in liste then i would like to keep in my df1 only the subset of names that verify this condition.

3- do the same 2 checks for my vector ind1.

I was able to do the 3 checks but not the last one for ind1.

the expected output will be :

# check 1
# no problem
 any(myvec %in% names(df1))
 [1] TRUE

# check 2
# no problem 

if(any(myvec %in% liste)){
  df1=cbind(df1[1],df1[,names(df1) %in% myvec])
}
  ID1 A B G
1   1 1 2 5
2   2 1 2 5
3   3 1 2 5

# check 3
# no rpoblem
 any(myvec %in% names(ind1))
[1] TRUE

# check 4
# where i got stocked i tried to repeat the same code in check 2 but i got an error for dimension in vector
# expected output 
ind1
ID2   A   B   G 
  1   2   2   6 

Any help will be appreciated or resources about handling names in vectors. Thank you in advance


Solution

  • Is this what you are looking for?

    if(any(myvec %in% liste)){
      ind1=c(ind1[1],ind1[names(ind1) %in% myvec])
    }