roastbeeef
roastbeeef

Reputation: 1119

Apply and custom function to add calculated fields to dataframe in R

I've browsed R for an hour or so trying to find an answer to a problem I'm having and I can't work it out based on the answers I've seen so far. I need to add a list of calculated values into a new column within a dataframe. I've tried doing this with an if statement but was having no luck, I've been trying to complete this exercise with the apply function and a custom function.

Theoretically this is my data:

a <- 1:5
b <- 1:5
c <- 1:5
 
df <- data.frame(a,b,c) 

  a b c
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5

This is the function that I wish to embed within the lapply function.

func <- function(x){
  (((x/1000)*b)+c)
}

When I try and run this:

lapply(df, function(x) {(((x/1000)*b)+c)})

I get the following output:

$a
[1] 1.001 2.004 3.009 4.016 5.025

$b
[1] 1.001 2.004 3.009 4.016 5.025

$c
[1] 1.001 2.004 3.009 4.016 5.025

Which I'm sure is right, but it's not what I'm looking for, what I'm trying to generate is column D, which would be (((a/1000)*b)+c).

Upvotes: 1

Views: 663

Answers (1)

Tonio Liebrand
Tonio Liebrand

Reputation: 17699

Simply this?

a <- 1:5
b <- 1:5
c <- 1:5

df <- data.frame(a,b,c) 
(df$d <- ((df$a/1000)*df$b)+df$c)

Upvotes: 3

Related Questions