[R] nested looping functions and dataframes
Lanna Jin
lannajin at gmail.com
Tue Mar 16 17:31:25 CET 2010
Hey All,
So, I am confused how exactly to use nesting loop functions in R to spit out
data frames. I've managed to create a working function for my data set that
generates a data frame for a given set of Year i and Location j; but how
would I do it for all Years and Locations?
Here is my working function:
test<-function(i,j){
a<-x[which(x$Year==i & x$Location==j),]
b<-as.data.frame(as.matrix(table(a$Species,a$Species)))
c<-b[-which(b$Var1==b$Var2),-3]
c$Year<-i; c$Location<-j
return(c)
}
Where, x is a dataframe that looks like the following:
> head(x,n=20)
Year Location Species
66 1998 PIPE_7 ACMI2
67 1998 PIPE_7 AMAR2
68 1998 PIPE_7 AMCA6
69 1998 PIPE_7 ANCY
70 1998 PIPE_7 ASVE
71 1998 PIPE_7 BOCU
72 1998 PIPE_7 CIFL
73 1998 PIPE_7 DAPU5
74 1998 PIPE_7 DICHANTHEL
75 1998 PIPE_7 GABO2
76 1998 PIPE_7 HEHE5
77 1998 PIPE_7 LIAS
78 1998 PIPE_7 LIPY
79 1998 PIPE_7 PAVI2
80 1998 PIPE_7 PHPI
81 1998 PIPE_7 PHVI5
82 1998 PIPE_7 RAPI
83 1998 PIPE_7 SOCA6
84 1998 PIPE_7 VIPE2
85 1998 PIPE_7 ZIAU
and when feeding x into my function "test" with the parameters i = 1998 and
j = "PIPE_7", I get the following dataframe, c:
> head(test(1998,"PIPE_7"),n=20)
Var1 Var2 Year Location
2 AMAR2 ACMI2 1998 PIPE_7
3 AMCA6 ACMI2 1998 PIPE_7
4 ANCY ACMI2 1998 PIPE_7
5 ASVE ACMI2 1998 PIPE_7
6 BOCU ACMI2 1998 PIPE_7
7 CIFL ACMI2 1998 PIPE_7
8 DAPU5 ACMI2 1998 PIPE_7
9 DICHANTHEL ACMI2 1998 PIPE_7
10 GABO2 ACMI2 1998 PIPE_7
11 HEHE5 ACMI2 1998 PIPE_7
12 LIAS ACMI2 1998 PIPE_7
13 LIPY ACMI2 1998 PIPE_7
14 PAVI2 ACMI2 1998 PIPE_7
15 PHPI ACMI2 1998 PIPE_7
16 PHVI5 ACMI2 1998 PIPE_7
17 RAPI ACMI2 1998 PIPE_7
18 SOCA6 ACMI2 1998 PIPE_7
19 VIPE2 ACMI2 1998 PIPE_7
20 ZIAU ACMI2 1998 PIPE_7
21 ACMI2 AMAR2 1998 PIPE_7
I have searched through the R-help archives for hints, which have not been
successful in answering my question. As a new user to R and programming
languages, I truly appreciate your help and thank you for your patience.
Thanks in advance for your response,
Lanna Jin
-----
Lanna Jin
lannajin at gmail.com
510-898-8525
--
View this message in context: http://n4.nabble.com/nested-looping-functions-and-dataframes-tp1595166p1595166.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list