0

I would like to create new column in data.frame as following:

Data description:

`'data.frame':  20 obs. of  3 variables:
 $ gvkey            : int  1004 1004 1004 1004 1004 1004 1004 1004 1004 1004 ...
 $ DEF              : int  0 0 0 0 0 0 0 0 0 0 ...
 $ FittedRobustRatio: num  0.549 0.532 0.519 0.539 0.531 ...`

Function I wrote and doesn't work:

fun.mark <- function(x,y){
   if (x==0) { y[y>0.60] <- "Del"
   } else (x==1) {
y[y<0.45] <- "Del2"}}

NewDataFrame <- ddply(ShorterData,~gvkey,transform,Fitcorr=fun.mark(DEF, FittedRobustRatio))

So basically what I want to do is to look into DEF column if 0 and FittedRobustRatio > 0.60 then replace the value with "Del" and if column DEF is 1 (there are only 0 or 1 values in the column) then look into FittedRobustRatio column and replace values where <0.45 with for example "Del2". Thanks.

Maximilian
  • 4,177
  • 7
  • 46
  • 85

1 Answers1

0

To do this I normally nest ifelse commands, ifelse sets out like this:

ifelse(definition e.g. a>b, gets "x" if definition met, gets "y" if definition not met)

So this should work...

data.frame$new.column <- ifelse (
   data.frame$DEF=="0"&data.frame$FittedRobustRatio>0.6, "Del", ifelse(
      data.frame$DEF=="1"&data.frame$FittedRobustRatio<0.45, "Del2", "none"))

I could be wrong as you have not provided a reproducible dataframe so I can't test this.

rg255
  • 4,119
  • 3
  • 22
  • 40
  • Thanks, it kind of works. Leaves however "none" instead numbers but thats okay. – Maximilian Jul 18 '13 at 08:58
  • @Max What numbers would you like in there? if it is the FittedRobust.. number then replace "none" with data.frame$FittedRobustRatio - don't forget to accept the answer if it works :) – rg255 Jul 18 '13 at 09:00
  • 1
    oh yes, sorry I didn't look properly into your code! Sure the "none" is to be just replaced as you noted :) – Maximilian Jul 18 '13 at 09:10