Reputation: 15
I am sure the answer is simple, but I did a lot a searching the last days, but apparently not able to figure out the right thing to do.. The problem is: I have imported a dataset via RODBC that shows what how much profit each user is generating
userdata <- sqlQuery(channel, query)
userdata
USER P1 P2 P2 P3
1 322 459 354 349 699
2 232 249 311 349 699
3 433 390 393 349 699
Then I have made a 4 functions that have their own set of conditions, and they will simply return a number, customer lifetime value. I like to use the functions on each of the columns P1,P2,P2,P4. For example apply clvP1() for each element in column P1 and so on. End result begin that the values in 'userdata' are updated, so I can send this back to database.
So if anyone has a tip, please let me know.
thanks,
Upvotes: 1
Views: 2981
Reputation: 19783
To apply function clvP1
on column P1
of a data frame simply:
userdata$P1 = clvP1(userdata[,'P1'])
Complete solution:
new_userdata = with(userdata, data.frame(USER=USER, P1=clvP1(P1), P2=clvP2(P2),
P3=clvP3(P3), P4=clvP4(P4)))
Upvotes: 2
Reputation: 93813
Here's a worked example of how you could apply specific functions to specific columns:
Example data:
test <- data.frame(a=1:3,b=4:6)
test
a b
1 1 4
2 2 5
3 3 6
Define functions as columnname+"fun"
afun <- function(x) {exp(x)}
bfun <- function(x) {log(x)}
Apply afun
to col a
and bfun
to col b
and so on...
data.frame(
mapply(
function(x,y) do.call(y,list(x)),
test,
paste(names(test),"fun",sep=""),
SIMPLIFY=FALSE
)
)
Result
# exp(a) log(b) as defined by afun and bfun
a b
1 2.718282 1.386294
2 7.389056 1.609438
3 20.085537 1.791759
Upvotes: 1