DLYRR :: MANIP: Come utilizzare Argomenti stringa (tenendo conto dei colni) anziché i nomi delle colonne

StackOverflow https://stackoverflow.com//questions/25075312

  •  26-12-2019
  •  | 
  •  

Domanda

Il titolo descrive praticamente quello che voglio:

invece di:

filter(mtcars, cyl == 8)
.

Vorrei usare:

var <- "cyl"
filter(mtcars, var == 8)  # pseudocode
.

Proprio come

mtcars[which(mtcars[,var]==8),]
.

Vedo che ci sono funzioni come starts_with(). Ma IMHO nessuno si adatta davvero a un'applicazione sopra semplice.

È stato utile?

Soluzione

Prova questo:

mtcars %>% do(filter(., .[[var]] == 8))
.

Altri suggerimenti

eval(substitute(filter(mtcars, var == 8),list(var=as.name(var))))%>%
head(2)
#    mpg cyl disp  hp drat   wt  qsec vs am gear carb
# 1 18.7   8  360 175 3.15 3.44 17.02  0  0    3    2
# 2 14.3   8  360 245 3.21 3.57 15.84  0  0    3    4

filter(mtcars, get(var, envir=as.environment(mtcars)) == 8) #should also work but not recommended
.

Ecco un altro modo con do.call:

do.call(filter, list(mtcars, bquote(.(as.name(var)) == 8)))
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top