如何根据我在 DF2 中获得的重要变量对 DF1 中的列变量进行子集化? [英] How do I subset column variables in DF1 based on the important variables I got in DF2?
问题描述
我有 2 个这样的 df
I have 2 df's like this
ID = c('x1','x2','x5')
df1 <- data.frame(ID)
x1 = c(1,2,3,4,5)
x2 = c(11,12,13,14,15)
x3 = c(21,22,23,24,25)
x4 = c(31,32,33,34,35)
x5 = c(41,42,43,44,45)
df2 <- data.frame(x1,x2,x3,x4,x5)
期望的输出
x1 x2 x5
1 1 11 41
2 2 12 42
3 3 13 43
4 4 14 44
5 5 15 45
我希望我的新数据集仅包含那些在 df1 中标识为重要的变量(即:x1、x2、x5)以及来自 df2 的值.
I would like my new dataset to contain only those variables that are identified in df1 as important (i.e: x1,x2,x5) with the values from df2.
在这个简单的数据集中,我知道我可以做到这一点,但只是删除 df2 中的 x3、x4,但理想情况下,我想将其应用于一个更大的数据集,其中我有 100 多个变量,因此想以编程方式进行.
In this simple dataset, I know I could do this but just removing x3,x4 in df2 but ideally I would like to apply it to a larger data set where I have more than 100 variables and hence would like to do it programatically.
推荐答案
我找不到一个骗子,所以这里是 - 简单地将 as.character(df1$ID)
的值作为子集作为在
I can't find a dupe so here goes- simply subset by the values of as.character(df1$ID)
as in
df2[as.character(df1$ID)] ## Or just `df2[df1$ID]` if its already a character
# x1 x2 x5
# 1 1 11 41
# 2 2 12 42
# 3 3 13 43
# 4 4 14 44
# 5 5 15 45
as.character
的原因是为了避免通过df1$ID
底层存储模式(整数)而不是它的级别进行子设置
The reason for as.character
is in order to avoid sub-setting by df1$ID
underlying storage mode (integer) rather by it's levels
虽然这个问题被标记为data.table
,所以我们也可以通过引用来做到这一点(如果我们有一个data.table
)——不需要转换为字符
Though this question is tagged with data.table
, so we could also do this by reference (if we have a data.table
)- no need to convert to character
setDT(df2)[, setdiff(names(df2), df1$ID) := NULL]
df2
# x1 x2 x5
# 1: 1 11 41
# 2: 2 12 42
# 3: 3 13 43
# 4: 4 14 44
# 5: 5 15 45
这篇关于如何根据我在 DF2 中获得的重要变量对 DF1 中的列变量进行子集化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!