Here is my data frame called cat_data
print(cat_data)
Metrics 2016 2017 2018
Number of Cats 100 120 150
Number Leaving 32 40 65
Number Staying 68 80 85
Percent of Leavers .32 .33 .43
Percent of Stayers .68 .67 .57
I want to convert only rows and 5 to percents with the percent symbol.
Here is my desired output.
Metrics 2016 2017 2018
Number of Cats 100 120 150
Number Leaving 32 40 65
Number Staying 68 80 85
Percent of Leavers 32% 33% 43%
Percent of Stayers 68% 67% 57%
I tried this but I couldn't get it to work.
cat_data[4:5,2:4] <- paste0(cat_data[4:5,2:4] * 100,%)
Can anyone tell me what I need to fix? thank you.
this should work as well
EDIT
The paste function requires a vector as input, but your input cat_data[4:5,2:4]
is a dataframe.
The apply
function takes array as input and outputs a vector.
cat_data[4:5,2:4] <- apply(cat_data[4:5,2:4]*100, 2, function(x) paste0(x, "%"))
you take your region of the data frame and multiply by 100. This will be your array input in the apply
function.
By indicating the margin = 2
the vectorization is performed by column. then you supply the function applied to the vector which in this case is the paste
function with your desired %
character.