Reputation: 143
I would like to filter table if I have column name written in variable. I tried bellow code but it did not work. dat is a data frame, name of column is Name, and I would like to filter by "John".
colname <- "Name"
dat[dat$colname %in% "John",]
I saw that it works fine if I do not use variable for column name. (Bellow code works fine)
dat[dat$"Name" %in% "John",]
Upvotes: 1
Views: 515
Reputation: 887088
With data.table
, we can use eval
with as.symbol
library(data.table)
setDT(dat)[eval(as.symbol(colname)) == "John"]
# Name X1 X2
#1: John 0.8646536 1.2688507
#2: John -1.7201559 -0.3125515
Upvotes: 0
Reputation: 388982
An approach with dplyr
using non-standard evaluation. Using @jay.sf's data
library(dplyr)
dat %>% filter(!!sym(colname) == "John")
# Name X1 X2
#1 John 0.864654 1.268851
#2 John -1.720156 -0.312552
In data.table
, we can use get
library(data.table)
setDT(dat)[get(colname) == "John"]
Since we have only one value to compare we can use ==
here instead of %in%
.
Upvotes: 0
Reputation: 72758
You may use the bracket function [
.
colname <- "Name"
dat[dat[[colname]] %in% "John", ]
dat[dat[, colname] %in% "John", ] # or
# Name X1 X2
# 8 John 0.8646536 1.2688507
# 9 John -1.7201559 -0.3125515
Data
dat <- structure(list(Name = structure(c(3L, 3L, 2L, 4L, 4L, 2L, 3L,
1L, 1L, 2L), .Label = c("John", "Linda", "Mary", "Olaf"), class = "factor"),
X1 = c(0.758396178001042, -1.3061852590117, -0.802519568703793,
-1.79224083446114, -0.0420324540227439, 2.15004261784474,
-1.77023083820321, 0.864653594565389, -1.72015589816109,
0.134125668141181), X2 = c(-0.0758265646523722, 0.85830054437592,
0.34490034810227, -0.582452690107777, 0.786170375925402,
-0.692099286413293, -1.18304353631275, 1.26885070606311,
-0.31255154601115, 0.0305712590978896)), class = "data.frame", row.names = c(NA,
-10L))
Upvotes: 2