简体   繁体   中英

Splitting a dataframe based on column names passed as a character vector

I have a data frame

df=data.frame(v1=c('abc','xyz','abc','abc'),v2=c(400,300,400,300),v3=c(1,2,3,4))



df
  v1  v2 v3
 abc 400  1
 xyz 300  2
 abc 400  3
 abc 300  4

I want to split this dataframe based on column v1 & v2. I know I can do it using the following command

a_split=split(df,list(df$v1,df$v2))

I get the desired result as follows:

> a_split[1]
$abc.300
   v1  v2 v3
4 abc 300  4

> a_split[2]
$xyz.300
   v1  v2 v3
2 xyz 300  2

> a_split[3]
$abc.400
   v1  v2 v3
1 abc 400  1
3 abc 400  3

The problem here is that the list of variables on which the data needs to be split will be passed by the user as a character vector. So it will be something like

var_name=c("v1","v2")

now if i try to use this vector directly I do not get the desired result

a_split=split(df,list(var_name))

Can someone suggest how to perform the split based on a list of character vectors

You could wrap in a function; where the variables are df for any data frame and col_choices for the columns to select.

f <- function(df, col_choices = NULL){
    if(is.data.frame(df) && !is.null(col_choices)){
        split(df, col_choices)
    }
}

Working off your example data:

> f(df = df, col_choices = c('v2', 'v3'))
$v2
   v1  v2 v3
1 abc 400  1
3 abc 400  3

$v3
   v1  v2 v3
2 xyz 300  2
4 abc 300  4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM