Reputation: 1338
I have a numeric data.frame that I would like to alter by pasting a %
behind each element.
A <- data.frame(A = seq(1,10,1))
apply(A,1, function(x) paste0(A[x,],"%"))
This works fine, however if the data has decimal place, apply
doubles each entry.
B <- data.frame(B = seq(1,5.5,0.5))
apply(B,1, function(x) paste0(B[x,],"%"))
It works with dplyr
:
require(dplyr)
B %>% mutate(B = paste0(B,"%"))
but I would like to understand why the apply solution fails.
Upvotes: 1
Views: 805
Reputation: 23788
You can try
sapply(B,paste0,"%")
Since the data frame examples in the OP consist of a single vector, it may be useful to show that this works for a general dataframe:
B <- data.frame(x1 = seq(1,10,1), x2=seq(1,5.5,0.5))
sapply(B,paste0,"%")
# x1 x2
# [1,] "1%" "1%"
# [2,] "2%" "1.5%"
# [3,] "3%" "2%"
# [4,] "4%" "2.5%"
# [5,] "5%" "3%"
# [6,] "6%" "3.5%"
# [7,] "7%" "4%"
# [8,] "8%" "4.5%"
# [9,] "9%" "5%"
#[10,] "10%" "5.5%"
Upvotes: 3