I want to subset data frame by value of group variable, for example, the group variable has values a, b, c, d, plan to subset data like this:
subData<- OriginalData %>% filter(group=="a")
Created a piece of code to perform this procedure,
subsetting <- function(x) {
subData<- OriginalData %>% filter(group=="group") }
function(a) #call the function to perform subsetting
function(b)
function(c)
function(d)
Tried couple times, it doesn't work, the problem probably is from "filter(group="group")", I know SAS can assign a subsetting value by a macro variable, it works like this: when group="&group". don't know how to deal with it in R. Any help will be highly appreciated! Thank you!
As you work to get a handle on R stuff, you might want to check out this thread:
Despite the opening topic description, there's quite a few resources there that are also appropriate for people who have some programming experience but in a very different language (e.g. SAS).
I suspect it has to do with using var to refer both to a column in the data frame as well as your parameter to filter from the grp field. This worked for me:
library(dplyr)
df <- expand.grid(var = 1:10, grp = c("A", "B"))
df$grp<- as.character(df$grp)
subsetting= function(data, grp_filter) {
return(data %>% filter(grp==grp_filter))
}
transit<- subsetting(data=df, grp_filter="A")
transit
#> var grp
#> 1 1 A
#> 2 2 A
#> 3 3 A
#> 4 4 A
#> 5 5 A
#> 6 6 A
#> 7 7 A
#> 8 8 A
#> 9 9 A
#> 10 10 A
I prefer the tidyverse code that others have proposed, but if you want a raw R solution, the keyword "subset" will do the job and will work just as well in a function:
#Create a subset of a data.frame or data.table
subData <- subset(OriginalData, group == "a")
If you wish to make your own then I suggest this function:
Thank you!
The reason is that the group has more than 30 values requested to be subset and the real function is more complicated, there are other procedure included in, planed to execute all procedure by one click.