R - ddply and incrementing a counter
I am using ddply
to split up a data frame and send the chunks to a function. Before the ddply
line, I set i=1
. Then inside the functi开发者_运维问答on I am incrementing i
so that each chunk of data gets a new number. When I run this, however, i
is being reset to 1 each time the function is called. I assume this is because the i
outside the function is being reassigned each time ddply
sends a new chunk of data. Is there a way to increment outside the function and send that number along with the data?
EDIT:: Here is the calling line:
rseDF <- ddply(rseDF, .(TestCompound), .fun = setTheSet)
Here is the function:
##Set The Set Column
setTheSet <- function(df) {
if (df[,"TestCompound"] == "DNS000000001") df[,"Set"] <- "Control"
else {df[,"Set"] <- i
i <<- i+1}
return(df)
}
That is just a normal scoping issue where you, if you insist on doing this, need to use <<-
for the global assignment:
R> library(plyr) ## load plyr
R> i <- 1 ## set counter
R> DF <- data.frame(a=rep(letters[1:3], each=3), b=1:9)
R> DF ## boring but simple data frame
a b
1 a 1
2 a 2
3 a 3
4 b 4
5 b 5
6 b 6
7 c 7
8 c 8
9 c 9
R> ddply(DF, .(a), function(x) mean(x$b)) ## summarized
a V1
1 a 2
2 b 5
3 c 8
R> ddply(DF, .(a), function(x) { i <<- i + 1; data.frame(i=i, res=mean(x$b)) })
a i res
1 a 2 2
2 b 3 5
3 c 4 8
R>
You could use assign
to change the value of the global variable from within your function:
> x <- 10
> test1 <- function() { x <- 3 }
> test1()
> x
[1] 10
> test2 <- function() { assign('x', 3, envir = .GlobalEnv) }
> test2()
> x
[1] 3
As you can see, test1
doesn't do what you expect, whereas test2
does.
edit: A more concise approach that I've just discovered by reading the manual is to use the "superassignment" operator <<-
:
> test3 <- function() { x <<- 17 }
> test3()
> x
[1] 17
The manual explains the semantics of the simple assignment within a function:
Note that any ordinary assignments done within the function are local and temporary and are lost after exit from the function. Thus the assignment
X <- qr(X)
does not affect the value of the argument in the calling program.
精彩评论