Creating new variables by writing a function

Hi, I'm doing a Biostatistics course and am trying to figure out how to make a new variable from a data set I already uploaded.
I want to label the variable "effect", and have it show the difference between the 'grass' samples and the 'spruce' samples of each 'box' as shown in the console.
Seems like there's probably a simple solution but can't find anything.

One solution is

spruce$effect <- spruce$Spruce - spruce$Grass
1 Like

Hi, next time please provide a reproducible example instead of a screenshot.

Anyway, here is some code that should work. You could also calculate the absolute difference with the abs() function.


# tidyverse way
spruce <- spruce %>% 
  mutate(diff = Grass - Spruce) 

# base R way
spruce$diff <- spruce$Grass - spruce$Spruce

Thank you this helped a lot.

1 Like

Hi sorry I'm new here on the forum, will definitely do that next time!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.