当变量名称与data.table中的现有列名称相同时,如何使用变量对data.table进行子集设置?它可以与get("varname",pos = 1)
一起使用,但是还有更健壮/灵活的解决方案吗?
library(data.table)
my_data_frame <- data.frame(
"V1"=c("A","B","C","A"),
"V2"=c(1, 2, 3, 4),
stringsAsFactors = FALSE
)
V1 <- "A"
my_data_table <- as.data.table(my_data_frame)
# Can I improve this a bit? I want rows where V1 == "A", but use V1 in the statement
my_data_table[ my_data_table$V1 == get("V1", pos = 1), ]
重命名V1
是不可选项。
更新:我不认为这是100%的重复。对于我的问题,this question的可接受答案是不可接受的,因为它使用了我不想使用的显式get
,如评论中所述。
答案 0 :(得分:3)
这是使用library(tidyverse)
的解决方案:
library(data.table)
library(tidyverse)
my_data_frame <- data.frame(
"V1"=c("A","B","C","A"),
"V2"=c(1, 2, 3, 4),
stringsAsFactors = FALSE
)
V1 = "A"
my_data_table <- as.data.table(my_data_frame)
df = my_data_table %>% filter(V1 == !!get("V1")) #you do not have to specify pos = 1
如果您想让R使用名为“ V1”的对象,您可以这样做
V1 = "A"
list_test = split(my_data_table, as.factor(my_data_table$V1)) #create a list for each factor level of the column V1.
df = list_test[[V1]] #extract the desired dataframe from the list using the object "V1"
是您想要的吗?
答案 1 :(得分:3)
如果您不介意分两步进行操作,则可以将其子集排除在data.table
的范围之外(尽管使用data.table时通常不希望这样做。) ):
wh_v1 <- my_data_table[, V1]==V1
my_data_table[wh_v1]
# V1 V2
#1: A 1
#2: A 4
答案 2 :(得分:1)
对于相等条件,可以使用联接:
mDT = data.table(V1)
my_data_table[mDT, on=.(V1), nomatch=0]
# V1 V2
# 1: A 1
# 2: A 4
x[i, on=.(V1)]
中的连接条件为
V1 == V1
其中LHS来自x
,而RHS来自i
。就像在i
中对x
的每一行的查找一样。 nomatch=0
意味着从输出中删除在i
中找到但未在x
中找到的任何值...例如
mDT2 = data.table(V1 = c("A", "D"))
my_data_table[mDT2, on=.(V1)]
# V1 V2
# 1: A 1
# 2: A 4
# 3: D NA
my_data_table[mDT2, on=.(V1), nomatch=0]
# V1 V2
# 1: A 1
# 2: A 4