简体   繁体   中英

How to add a new column in data frame by dividing values in an existing column, specifically, in the same existing column?

I want to use the mutate function to create a new column.

I can't figure out how to do it because the values in the new column are to be quotients of values from another column in my data frame.

Usually when I've used mutate before the values were in different columns like mutate(newcolumn = colX_values / colY_values) but this time, both parts of the equation are in the same column. The main difference is that I want the female values to be divided by the male values.

```{r}
library(tidyverse)
library(ggplot2)
library(readxl)
```

```{r}
race = c("all", "all", "black", "black")
earnings = c(74467, 57202, 44725, 40974)
gender = c("male", "female", "male", "female")
work_status = c("FT", "FT", "FT", "FT")

data.frame(race, earnings, gender, work_status)
```

```{r}
earnings %>%
  filter(work_status == "FT")
```

I eventually want a 5th column that consists of the the female earnings / male earnings per each race. so for all the male rows there should be the number 1 in the new column and in all the female rows it should be the result of 57202/74467.

I am just not sure how to get that result.

Is this what you're looking for?

df %>% 
  spread(gender,earnings) %>% 
  mutate(Ratio=female/male)

Output:

 race work_status female  male     Ratio
1   all          FT  57202 74467 0.7681523
2 black          FT  40974 44725 0.9161319

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM