通过可变数量的特定列R子集数据帧

时间:2014-02-18 11:53:04

标签: string r subset

这个人现在已经困扰了我几天了,我还没有在堆栈交换上运气好。基本上,我有两个表,一个表定义从第二个表中选择的列(按列号)。我最初的计划是将列串在一起并将其传递给subselect语句,但是当我将字符串定义为as.character时,它并不开心,即:

# Data Sets, Variable_Selection: Table of Columns to Select from Variable_Table

VARIABLE_SELECTION <- data.frame(Set.1 = c(3,1,1,1,1), Set.2 = c(0,3,2,2,2), Set.3 = c(0,0,3,4,3),
                                 Set.4 = c(0,0,0,5,4), Set.5 = c(0,0,0,0,5))

VARIABLE_TABLE <- data.frame(Var.1 = runif(100,0,10), Var.2 = runif(100,-100,100), Var.3 = runif(100,0,1),
                             Var.4 = runif(100,-1000,1000), Var.5 = runif(100,-1,1), Var.6 = runif(100,-10,10))

# Sting rows into character string of columns to select

VARIABLE_STRING <- apply(VARIABLE_SELECTION,1,paste,sep = ",",collapse = " ")
VARIABLE_STRING <- gsub(" ",",",VARIABLE_STRING)
VARIABLE_STRING <- data.frame(VAR_STRING = gsub(",0","",VARIABLE_STRING))

# Will actually be part of lapply function but, one line selection for demonstration:

VARIABLE_SINGLE_SET <- as.character(VARIABLE_STRING[4,])

# Subset table for selected columns

VARIABLE_TABLE_SUB_SELECT <- VARIABLE_TABLE[,c(VARIABLE_SINGLE_SET)]

#  Error Returned:
#  Error in `[.data.frame`(VARIABLE_TABLE, , c(VARIABLE_SINGLE_SET)) : 
#  undefined columns selected

我知道文本格式是问题,但我找不到解决方法,有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您应该避免按列数进行子设置并按变量名称处理,或者至少将索引保留为整数列表(不需要强制转换为字符串)

首先要保持相同的想法,这会更正您的代码。 Basciaclly我强迫你的变量向量:

VARIABLE_TABLE[,as.numeric(unlist(strsplit(
        VARIABLE_SINGLE_SET,',')))]

答案 1 :(得分:1)

这是否会产生预期效果?

lapply(VARIABLE_SELECTION, function(x) VARIABLE_TABLE[ , x[x != 0], drop = FALSE])

生成一个列表,其中每个元素都是'VARIABLE_SELECTION'给出的'VARIABLE_TABLE'的子集(使用'VARIABLE_TABLE',行数较少)。

# $Set.1
#       Var.3    Var.1  Var.1.1  Var.1.2  Var.1.3
# 1 0.09536403 5.593292 5.593292 5.593292 5.593292
# 2 0.09086404 6.339074 6.339074 6.339074 6.339074
# 
# $Set.2
#        Var.3    Var.2  Var.2.1  Var.2.2
# 1 0.09536403 65.81870 65.81870 65.81870
# 2 0.09086404 66.79157 66.79157 66.79157
# 
# $Set.3
#        Var.3     Var.4    Var.3.1
# 1 0.09536403 -674.6672 0.09536403
# 2 0.09086404 -576.7986 0.09086404
# 
# $Set.4
#        Var.5     Var.4
# 1  0.5155411 -674.6672
# 2 -0.9593219 -576.7986
# 
# $Set.5
#        Var.5
# 1  0.5155411
# 2 -0.9593219