Is l_ply
or some other apply-like function capable of inserting results to an existing data frame?
Here's a simple example...
Suppose I have the following data frame:
mydata <- data.frame(input1=1:3, input2=4:6, result1=NA, result2=NA)
input1 input2 result1 result2
1 1 4 NA NA
2 2 5 NA NA
3 3 6 NA NA
I want to loop through the rows, perform operations, then insert the answer in the columns result1
and result2
. I tried:
l_ply(1:nrow(mydata), function(i) {
mydata[i,"result1"] <- mydata[i,"input1"] + mydata[i,"input2"]
mydata[i,"result2"] <- mydata[i,"input1"] * mydata[i,"input2"]})
but I get back the original data frame with NA's
in the result columns.
P.S. I've already read this post, but it doesn't quite answer my question. I have several result columns, and the operations I want to perform are more complicated than what I have above so I'd prefer not to compute the columns separately then add them to the data frame after as the post suggests.