Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use dplyr to select columns

Tags:

r

dplyr

subset

I'm trying to use the select function of dplyr to extract columns of another dataframe.

Here the data frame:

dput(df1)
structure(list(Al = c(30245, 38060, 36280, 24355, 27776, 35190, 
38733.8, 36400, 29624, 33699.75), As = c(9, 8.75, 13.5, 7.75, 
7.6, 8.33, 8, 8.75, 7.4, 8.25), Cd = c(0.15, 0.13, 0.15, 0.1, 
0.16, 0.13, 0.24, 0.15, 0.22, 0.13), Cr = c(108.5, 111.75, 104.5, 
81.25, 93.2, 109.75, 105, 104, 87.8, 99.75), Hg = c(0.25, 0.35, 
0.48, 1.03, 1.12, 0.2, 1.14, 0.4, 2, 0.48)), row.names = c(NA, 
10L), class = "data.frame", .Names = c("Al", "As", "Cd", "Cr", 
"Hg"))

and here the character vector I want to use as filter:

dput(vec_fil)
c("Elemento", "As", "Cd_totale", "Cr_totale", "Cu_totale", "Hg", 
"Ni_totale", "Pb_totale", "Zn_totale", "Composti_organostannici", 
"PCB_totali", "Sommatoria_DDD", "Sommatoria_DDE", "Sommatoria_DDT", 
"Clordano", "Dieldrin", "Endrin", "Esaclorocicloesano", "Eptacloro_epossido", 
"Sommatoria_IPA", "Acenaftene", "Antracene", "Benzo.a.antracene", 
"Benzo.a.pirene", "Crisene", "Dibenzo.ac._.ah.antracene", "Fenantrene", 
"Fluorantene", "Fluorene", "Naftalene", "Pirene")

As you can see vec_fil has many characters that don't match the columns of df1, so I get this error:

require("dplyr")
df2 <- select(df1, one_of(vec_fil))
Error: Each argument must yield either positive or negative integers

Any hint I can use in order to get only the matched character of the filter vector in the new data frame?

like image 393
matteo Avatar asked Mar 24 '15 09:03

matteo


1 Answers

you can try this code in base R

df1[, names(df1) %in% vec_fil]

and if you want to use package dplyr

select(df1, which(names(df1) %in% vec_fil))
like image 86
Mamoun Benghezal Avatar answered Oct 13 '22 18:10

Mamoun Benghezal