Homap
Homap

Reputation: 2214

Is it possible to pass a character vector of variable length to R function?

In the function below:

subset_data <- function(coldata, a, b){
    coldata <- coldata[, c(a, b)]
    return(coldata)
} 

c(a, b) is having only two elements, a and b. Is it possible to make it flexible so the user can pass any number of elements, i.e., to have for example c(a, b, c, d) or any other possibilities?

Example of coldata

sample tissue species time condition
s1 liver mouse morning treated
s2 liver mouse morning treated
s3 brain fly evening untreated

Usage of function

subset_data(coldata, d = c("tissue", "species")

Desired change:

subset_data(coldata, d = c("tissue", "species", "time")

or

subset_data(coldata, d = c("tissue", "species", "time", "condition")

Thanks!

Upvotes: 0

Views: 144

Answers (2)

linog
linog

Reputation: 6226

Many ways to do that. I think the easiest solutions involve simply to use string vectors. You could also use ... but in your example this is an unecesseray complication. I propose you data.table or dplyr syntax :

data.table

library(data.table)
subset_data <- function(data, cols = c('a','b')){
  data2 <- data.table::as.data.table(data)
  return(data2[,.SD,.SDcols = cols])
}

dplyr

library(dplyr)
subset_data <- function(data, cols = c('a','b')){
  data %>% dplyr::select(cols)
}

Upvotes: 1

James Curran
James Curran

Reputation: 1294

Given it seems you just want to be able select specific columns, why not use select from dplyr? E.g.

df = data.frame(tissue = sample(c("brain", "liver", "kidney"), 10, replace = TRUE),
                species = sample(c("mouse", "cat", "dog"), 10, replace = TRUE),
                time = sample(c("day", "evening", "night"), 10, replace = TRUE),
                condition = sample(c("dead", "alive"), 10, replace = TRUE))

Then just select the columns you want, e.g.

library(dplyr)
df %>%
  select(tissue, species)

or

df %>%
  select(tissue, species, time)

Upvotes: 0

Related Questions