Hardik gupta Hardik gupta - 3 years ago 170
R Question

Select data frame based on condition without for loop

I have 3 data frames

df1
,
df2
,
df3


Based on year condition, I want to select one of them

My current approach is using for-loops. Can I do this better?

if(year == "2008"){
df <- df1
} else if (year == "2009"){
df <- df2
} else{
df <- df3
}

Answer Source

I would just keep them in a list. Something like :

lst <- list('2008'= df1, '2009' = df2, '2010' = df3)

and then based on the year I would subset it. Basically now you replace your entire code with just one line.

lst[year]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download