Paige
Paige

Reputation: 1

R: applying multiple math expressions row-wise

I'm still very new to R and I am trying to apply 3 different equations using values from every row of a dataframe, called x. The variables in the equations are values from certain columns in x. I want to finish with the results of the equations as it's own dataframe/table with the first column of the initial dataframe included as well.

Here Is an example for my dataframe x.

   column1     name1      name2     name3     name4     name5
         A  85.30000 0.07700000  38.00000       NaN       NaN
         B  19.20000 0.53466667       NaN       NaN       NaN
         C  56.06667 0.38333333       NaN       NaN       NaN
         D  94.51667 0.12000000  19.00000       NaN  43.00000
         E  18.80000 0.24000000  12.00000  1.000000   9.50000

There is actually 100+ rows in x. Column1 represents names (each row is a different name), and the rest of the columns are different variables/parameters. The rows are essentially data that "belongs" to the name in Column1 (the order of the values within each column matters).

Here is what I used for the function

M.Est<-function(a,b,c,d){
    Lenth<-nrow(function(a,b,c,d))
    one<-4.99%*%(d^-0.916)
    two<-4.11%*%(a^0.73)%*%(b^-0.331)
    three<-a%*%(c%/%b)^-1.5
    return(data.frame(eval(one),eval(two),eval(three))) 
} 
M.columns=cbind(M.Est(name1,name2,name3,name4))
final=data.frame(x[,1],M.columns)
colnames(final,c("column1","Res_one","Res_two","Res_three")

Where x is my data frame, and (name1,name2,name3,name4) are each a column in the data frame x, I don't use every single column. This however, does not work, and I can't figure out how to integrate NaN values into this.

If there are NaN values in an input for any of the equations applied in any of the rows, I still want the equation results included in the output, as a Na/NaN. The order of the equation results columns NEEDS to match the order of the original rows in x (no data missing/removed) in order for them to correspond/match with the order of the first column in x (because values in column 1 of x represent names).

Here is an example of what I am looking for as "final" (these aren't what the actual values for the res columns should be)

   column1    Res_one    Res_two     Res_3
         A   85.30000 0.07700000  38.00000 
         B   19.20000 0.53466667       NaN 
         C   56.06667 0.38333333       NaN     
         D   94.51667 0.12000000  19.00000     
         E   18.80000 0.24000000  12.00000 

How should I go about fixing this?

Upvotes: 0

Views: 206

Answers (0)

Related Questions