我有一个数字data.frame,我想通过粘贴每个元素后面的%
来改变它。
A <- data.frame(A = seq(1,10,1))
apply(A,1, function(x) paste0(A[x,],"%"))
这样可以正常工作,但是如果数据有小数位,apply
会使每个条目加倍。
B <- data.frame(B = seq(1,5.5,0.5))
apply(B,1, function(x) paste0(B[x,],"%"))
适用于dplyr
:
require(dplyr)
B %>% mutate(B = paste0(B,"%"))
但我想了解为什么应用解决方案失败。
答案 0 :(得分:3)
你可以尝试
sapply(B,paste0,"%")
由于OP中的数据帧示例由单个向量组成,因此显示这适用于一般数据帧可能很有用:
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%"