Tiptop
Tiptop

Reputation: 623

New column with conditions in tidyverse

I want to add a column days to a dataset with some conditions. For each soil there should be nine rows in the days column. The first two rows (0 and 4) should be the value from the SS Period. The value for the days 10-66 should be the N in Period and the ES in Period should be the last days.

This is a very bad explanation I know, but I think perhaps it makes sense by looking at the expected_df dataset.

All help is very much appreciated!

df <- structure(list(soil = c(12L, 5L, 3L, 12L, 5L, 3L, 12L, 3L, 5L
), ITS_1 = c(290900, 16090, 12460, 0, 19700, 25000, 114.2, 39100, 
25090), Period = c("ES", "ES", "ES", "N", "N", "N", "SS", "SS", 
"SS")), row.names = c(NA, -9L), class = "data.frame")**strong text**

This is how the data should look like

expected_df <- structure(list(soil = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 12L, 12L, 12L, 12L, 12L, 12L, 
5L, 5L, 5L), ITS_1 = c(39100, 39100, 25000, 25000, 25000, 25000, 
12460, 12460, 12460, 25090, 25090, 19700, 19700, 19700, 19700, 
16090, 16090, 16090, 114.2, 114.2, 0, 0, 0, 0, 16090, 16090, 
16090), Period = c("SS", "SS", "N", "N", "N", "N", "ES", "ES", 
"ES", "SS", "SS", "N", "N", "N", "N", "ES", "ES", "ES", "SS", 
"SS", "N", "N", "N", "N", "ES", "ES", "ES"), days = c(0L, 4L, 
10L, 17L, 24L, 66L, 81L, 94L, 116L, 0L, 4L, 10L, 17L, 24L, 66L, 
81L, 94L, 116L, 0L, 4L, 10L, 17L, 24L, 66L, 81L, 94L, 116L)), class = "data.frame", row.names = c(NA, 
-27L))

Upvotes: 0

Views: 73

Answers (1)

Zaw
Zaw

Reputation: 1474

One solution is to create a dataframe and left_join().

library(dplyr)
df_join <- data.frame(days = c(0, 4, 10, 17, 24, 66, 81, 94, 116),
                      Period = rep(c("SS", "N", "ES"), times = c(2, 4, 3)))

df %>% 
  left_join(df_join, by = "Period")

#    soil    ITS_1 Period days
# 1    12 290900.0     ES   81
# 2    12 290900.0     ES   94
# 3    12 290900.0     ES  116
# 4     5  16090.0     ES   81
# 5     5  16090.0     ES   94
# 6     5  16090.0     ES  116
# 7     3  12460.0     ES   81
# 8     3  12460.0     ES   94
# 9     3  12460.0     ES  116
# 10   12      0.0      N   10
# 11   12      0.0      N   17
# 12   12      0.0      N   24
# 13   12      0.0      N   66
# 14    5  19700.0      N   10
# 15    5  19700.0      N   17
# 16    5  19700.0      N   24
# 17    5  19700.0      N   66
# 18    3  25000.0      N   10
# 19    3  25000.0      N   17
# 20    3  25000.0      N   24
# 21    3  25000.0      N   66
# 22   12    114.2     SS    0
# 23   12    114.2     SS    4
# 24    3  39100.0     SS    0
# 25    3  39100.0     SS    4
# 26    5  25090.0     SS    0
# 27    5  25090.0     SS    4

Upvotes: 1

Related Questions