# Using functions to change values in a data.frame

5 messages
Open this post in threaded view
|

## Using functions to change values in a data.frame

 I'm having trouble with something that looks easy. (And I'm sure it will be easier within about 1 minute of receiving my first response.) Thanks in advance. I have a collection of data frames that I need to add columns, do some calculations and then fill in the new columns. Since I have a large number of similar data frames I want to do this with functions to make the code more readable and ensure that every frame is done the same way. However my simple example doesn't work as I expected it to: Here the R example code to cut and paste. The basic idea is to copy positive values of y into p and negative values into l. AddCols = function (MyFrame) {         MyFrame\$p<-0         MyFrame\$l<-0         return(MyFrame) } BinPosNeg = function (MyFrame) {         ifelse(MyFrame\$y>0,  MyFrame\$p<-MyFrame\$y,  MyFrame\$l My results below are weird. After the last function call F1 acts like BinPosNeg always evaluated MyFrame\$y>0. All updates went into p - none into l. What am I doing wrong? Thanks, Mark MY RESULTS: > AddCols = function (MyFrame) { + MyFrame\$p<-0 + MyFrame\$l<-0 + return(MyFrame) + } > > BinPosNeg = function (MyFrame) { + ifelse(MyFrame\$y>0,  MyFrame\$p<-MyFrame\$y,  MyFrame\$l > F1 <- data.frame(x=1:10, y=-4:5) > F1     x  y 1   1 -4 2   2 -3 3   3 -2 4   4 -1 5   5  0 6   6  1 7   7  2 8   8  3 9   9  4 10 10  5 > F1 <- AddCols(F1) > F1     x  y p l 1   1 -4 0 0 2   2 -3 0 0 3   3 -2 0 0 4   4 -1 0 0 5   5  0 0 0 6   6  1 0 0 7   7  2 0 0 8   8  3 0 0 9   9  4 0 0 10 10  5 0 0 > F1 <- BinPosNeg(F1) > F1     x  y  p l 1   1 -4 -4 0 2   2 -3 -3 0 3   3 -2 -2 0 4   4 -1 -1 0 5   5  0  0 0 6   6  1  1 0 7   7  2  2 0 8   8  3  3 0 9   9  4  4 0 10 10  5  5 0 > ______________________________________________ [hidden email] mailing list https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code. markknecht@gmail.com
Open this post in threaded view
|

## Re: Using functions to change values in a data.frame

Open this post in threaded view
|