-4

forest area to the I want to add a column name (say ForestAreaPerPopn) to find the ratio of forest area to the population(represented by variable Total below) residing. The data contains the following variables and their values. enter image description here

How can I add a column named ForestAreaPerPopn in Table****ForestAreaPerPop (shown below) so that the column contains the data calculated as ratio of forest area to Total.

Prabhakar
  • 61
  • 8
  • `df$ForestAreaPerPopn <- df$ForestArea / df$Total`. – Pax May 27 '22 at 17:08
  • Error in df$ForestArea : object of type 'closure' is not subsettable is returned. – Prabhakar May 27 '22 at 17:19
  • 1
    My comment just tells you: it is possible to add a variable `a` to a dataframe `df`, which is the ratio of two variables `b` and `c` by typing `df$a <- df$b / df$c`. Of course, you need to rename the variables according to your needs, e.g. your `b` is probably `Total`. If you expect further help on this very basic question, please provide data by `dput(head(df))`, replace `df` with the name of your dataframe. See https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Pax May 27 '22 at 17:23

1 Answers1

0

Too long for a comment.

You have a couple of problems. First, your column names have spaces and other special characters. This is allowed but creates all kinds of problems later. I suggest you do something like:

colnames(ForestAreaPerPop) <- gsub(' |\\(|\\)', '_', colnames(ForestAreaPerPop))

This will replaces any spaces, left or right parens in the colnames with '_'.

Then, something like:

ForestAreaPerPop$n <- with(ForestAreaPerPop, Forest_Area_in_ha/Total)

should give you what you want.

Some advice: long table names and column names may seem like a good idea, but you will live to regret it. Make them short but meaningful (easier said than done).

jlhoward
  • 58,004
  • 7
  • 97
  • 140