I am struggling to reference columns with a function.
Take the data:
dat = data.frame(height = c(20, 20, 40, 50, 60, 10), weight = c(100, 200, 300, 200, 140, 240),
age = c(19, 20, 20, 19, 10, 11))
Age_list <- c(19)
Take the example:
toy_func <- function(df,list,column){
for (i in list){
toy_output <- df[,column == i]
}
Return(toy_output)
}
And run:
tst <- toy_func(dat,Age_list,"age")
The output is a dataframe with no variables. I would like to generate an output where the initial dataframe dat has been filtered by ages that equal 19.
The loop is necessary as I plan to iterate through each unique item in the age column. Essentially i am writting a function to partition a dataframe by the unique values in one of its columns.
Thanks in advance, John
splitfunction. See what happens withsplit(mtcars, mtcars$gear)toy_output <- df[df[[column]] == i]$splitas @phiver mentioned. In your case you can check it withsplit(dat, dat$age). Is this the output you wanted?