Reputation: 1118
I am interested in displaying the values from two different tables as a combined table, with values and percentages displayed in the same cell.
I have two dataframes,
pf<-data.frame(alpha=c(17,42,19),beta=c(21,47,15),sea=c(19,43,21))
and
cf<-data.frame(alpha=c(417,242,119),beta=c(721,447,315),sea=c(819,443,921))
The percentages are housed in pf and the raw values for this year are in cf.
My desired output is:
desired<-data.frame(alpha=c("417 (17%)","242 (42%)","119 (19%)"),
beta=c("721 (21%)","447 (47%)","315 (15%)"),
sea=c("819 (19%)","443 (43%)","921 (21%)"))
which looks like:
alpha beta sea
1 417 (17%) 721 (21%) 819 (19%)
2 242 (42%) 447 (47%) 443 (43%)
3 119 (19%) 315 (15%) 921 (21%)
I am hoping for a solution that does not require explicitly typing column names "alpha" etc. in the code, as my columns will change names when pointed at difference source files. The number of rows will also change, though pf and cf will always match one another in terms of dimensions.
It seems as though multiplication or other basic math functions where both tables are treated in relation to one another are easy (i.e pf*cf quickly returns a table of the values where relational multiplication is performed).
At this point, I've been experimenting with paste0() but getting unworkable results.
Thank you in advance for any help!
Upvotes: 2
Views: 73
Reputation: 887058
We can use map2
from purrr
library(purrr)
map2_df(cf, pf, ~ sprintf("%d (%d%%)", .x, .y))
# A tibble: 3 x 3
# alpha beta sea
# <chr> <chr> <chr>
#1 417 (17%) 721 (21%) 819 (19%)
#2 242 (42%) 447 (47%) 443 (43%)
#3 119 (19%) 315 (15%) 921 (21%)
Or if it is float, then we can round
map2_df(cf, pf, ~ sprintf("%d (%f%%)", .x, round(.y, 2)))
Upvotes: 1
Reputation: 2987
An option in base
you use mapply
and paste0
:
as.data.frame(mapply(function(x, y) paste0(x, "(", y, "%)"), cf, pf))
alpha beta sea
1 417(17%) 721(21%) 819(19%)
2 242(42%) 447(47%) 443(43%)
3 119(19%) 315(15%) 921(21%)
Upvotes: 2