StudentOfScience
StudentOfScience

Reputation: 809

R dynamic data.frame subseting

I have a dataframe which is similar to this:

       A         B           C          D          E          F           G         H          I           J          K     origin
1 -0.7236848 -0.4245541  0.7083451  3.1623596  3.8169532 -0.04582876  2.0287920 4.409196 -0.3194430  5.9069321  2.7071142      1
2 -0.8317734  4.8795289  0.4585997 -0.2634786 -0.7881651 -0.37251184  1.0951245 4.157672  4.2433676  1.4588268 -0.6623890      1
3 -0.7633280 -0.2985844 -0.9139702  3.7480425  3.5672651  0.06220035 -0.3770195 1.101240  2.0921264  6.6496937 -0.7218320      1
4  0.8311566 -0.7939485  0.5295287 -0.5508124 -0.3175838 -0.63254736  0.6145020 4.186136 -0.1858161 -0.1864584  0.7278854      2
5  1.4768837 -0.7612165  0.8571546  2.3227173 -0.8568081 -0.87088020  0.2269735 4.386104  3.9009236 -0.6429641  3.6163318      2
6 -0.9335004  4.4542639  1.0238832 -0.2304124  0.8630241 -0.50556039  2.8072757 5.168369  5.9942144  0.6165200 -0.5349257      2

Note that the last variable is called origin; a factor label of levels 1 and 2; my real data set has more levels.

A function I am using requires this format:

result <- specialFuc(matrix1, matrix2, ....)

What I want to do, is write a function such that the input dataframe (or matrix) is split by "origin" then dynamically I would get multiple matrices to give to my "specialFuc"

my solution is:

for (i in 1:length(levels(df[,"origin"))){

    assign(paste("Var", "_", i, sep=''), subset(df, origin!=i)))
}

using this, I can create a list of names which I use get() to put in my special function.

As you can imagine this is not dynamic,... Any suggestions?

Upvotes: 1

Views: 61

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226427

I think something like

 do.call(specialFunc,
   split.data.frame(df[,-ncol(df)],df$origin))

should do it?

Upvotes: 2

Related Questions