[R] Subsetting a dataframe by dynamic column name

Sarah Goslee sarah.goslee at gmail.com
Thu Mar 27 16:30:38 CET 2014


There are many ways. You're making it overly complicated

Here, in an actual reproducible example (as you were requested to submit):

V <- data.frame(v1=c(1,0,0), v2=c("Shape", "Length", "Rate"),
stringsAsFactors=FALSE)
Finaldata <- data.frame(Shape = runif(5), Length = runif(5), Rate = runif(5))

# assuming names in V are not in the same order as columns in Finaldata
# also assuming there might accidentally be names not in Finaldata
Finaldata[, colnames(Finaldata) %in% V$v2[V$v1 == 0]]

# more elegant?
Finaldata[, colnames(Finaldata) %in% V$v2[!V$v1]]

# not robust to errors in V
Finaldata[, V$v2[!V$v1]]

# assumes order of column names matches order of V
Finaldata[, -V$v1]

Sarah

On Thu, Mar 27, 2014 at 11:09 AM, Sneha Bishnoi <sneha.bishnoi at gmail.com> wrote:
> Hi all!
>
> I am trying to drop columns from a data frame dynamically depending on user
> input. The dataframe whose columns need to be dropped is called "Finaldata"
> So here is what I do:
>
> V is a dataframe with columns v1 and v2 as follows
>
>    v1          v2
> 1   1      Shape
> 2   0       Length
> 3   0       Rate
>
> v1 corresponds to user input, 1 if you want to drop the column, 0 otherwise
> v2 corresponds to column names of the all the columns in "Finaldata"
> I then use following code to drop columns
>
> for (i in 1:3)
>   {
>     if(V$v1[i]==1)
>     {
>       print(V$v2[i])
>       Finaldata<-subset(Finaldata,select=-c(V$v2[i]))
>     }
>
>   }
>
> However v2 being type character is not accepted by subset.
> I read subset needs column names without quotes.
> I tried stripping off quotes through gsub and cat,however it din't help
> There are lot of columns and I cannot perform this individually on all
> columns.
> How do i go about it?
>
>
> Thanks!
> SB
>

-- 
Sarah Goslee
http://www.functionaldiversity.org




More information about the R-help mailing list