I have a large dataframe in which some columns contain long strings of comma-separated numerical data of unequal lengths, here the columns A, B, and C:
df <- data.frame(
id = 1:3,
A = c("200, 100, 80, 100","120, 210, 220", "170, 200"),
B = c("0.1, 0.2, 0.3","0.2, 0.3, 1.0, 0.4, 0.9", "0.55, 0.77, 0.99, 0.35"),
C = c("700.1, 701.0, 699.2", "702.5, 702.9", "705.4, 705.4, 706.0")
)
I need to calculate for this numerical data in A, B, and C the percentage change. I take it that to facilitate this, I need to separate each number into its own row using separate_rows. But how can I do this step for all three columns A, B, and C in one go?
All I can do is do it column by column - first for A, then for B, and finally for C:
library(tidyverse)
df %>%
# Step 1 - column `A`:
separate_rows(A, sep = ",", convert = TRUE) %>%
mutate(A_0 = lag((lead(A)-A)/A*100)) %>%
group_by(id) %>%
summarise(across(c(B,C), first),
A = paste0(A, collapse = ", "),
A_0 = paste0(A_0, collapse = ", ")
) %>%
ungroup() %>%
# Step 2 - column `B`:
separate_rows(B, sep = ",", convert = TRUE) %>%
mutate(B_0 = lag((lead(B)-B)/B*100)) %>%
group_by(id) %>%
summarise(across(c(A,A_0,C), first),
B = paste0(B, collapse = ", "),
B_0 = paste0(B_0, collapse = ", ")
) %>%
ungroup() %>%
# Step 3 - column `C`:
separate_rows(C, sep = ",", convert = TRUE) %>%
mutate(C_0 = lag((lead(C)-C)/C*100)) %>%
group_by(id) %>%
summarise(across(c(A,A_0,B,B_0), first),
C = paste0(C, collapse = ", "),
C_0 = paste0(C_0, collapse = ", ")
)
# A tibble: 3 × 7
id A A_0 B B_0 C C_0
<int> <chr> <chr> <chr> <chr> <chr> <chr>
1 1 200, 100, 80, 100 NA, -50, -20, 25 0.1, 0.… NA, 100, 50 700.1… NA, 0.12…
2 2 120, 210, 220 20, 75, 4.76190476190476 0.2, 0.… -33.33333333… 702.5… 0.471967…
3 3 170, 200 -22.7272727272727, 17.6470588235294 0.55, 0… -38.88888888… 705.4… 0.355669…
Is there a better way?