r - Function with multiple columns to get one output -
i want write function classify each row based on values within 3 columns either poor, medium or good
here illustration data
c = c(1, 0.4, 3, 6, 2) n = c(0.1, 3, 5, 7, 13) p = c(2, 3, 3, 4, 2) mydf = data.frame(c,n,p)
lets want classify things c < 0.5 poor, regardless of n or p. likewise values of n > 10
any values c such 1 < c < 4, , p such 1 < p < 4 classified good
everything else classified medium
currently have used several if functions checks each status @ time , final function see if required conditions final classification good, if there poor poor, otherwise medium.
instead way in 1 function because have expand many more conditions (20+). have tried using ifelse function couldn't figure out
if there sources read such functions appreciate input, thanks
try:
> mydf$result = with(mydf, ifelse(c<0.5 | n>10, 'poor',ifelse(c<4 & c>1 & p>1 & p<4, 'good', 'medium'))) > > mydf c n p result 1 1.0 0.1 2 medium 2 0.4 3.0 3 poor 3 3.0 5.0 3 4 6.0 7.0 4 medium 5 2.0 13.0 2 poor
to create function:
myfn = function(ddf){ ddf$res = with(ddf, ifelse(c<0.5 | n>10, 'poor',ifelse(c<4 & c>1 & p>1 & p<4, 'good', 'medium'))) ddf }
to write ifelse repeatedly:
ddf$res = with(ddf, ifelse(c<0.5 | n>10, 'poor', ifelse(c<4 & c>1 & p>1 & p<4, 'good', 'medium' )) # number of these closing brackets should same number of 'ifelse' ) # closing bracket 'with' function
r function
No comments:
Post a Comment