Reputation: 2214
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?
sample tissue species time condition
s1 liver mouse morning treated
s2 liver mouse morning treated
s3 brain fly evening untreated
subset_data(coldata, d = c("tissue", "species")
subset_data(coldata, d = c("tissue", "species", "time")
or
subset_data(coldata, d = c("tissue", "species", "time", "condition")
Thanks!
Upvotes: 0
Views: 144
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 :
library(data.table)
subset_data <- function(data, cols = c('a','b')){
data2 <- data.table::as.data.table(data)
return(data2[,.SD,.SDcols = cols])
}
library(dplyr)
subset_data <- function(data, cols = c('a','b')){
data %>% dplyr::select(cols)
}
Upvotes: 1
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