【问题标题】:How to convert a row of data to percent? R [duplicate]如何将一行数据转换为百分比? R [重复]
【发布时间】:2020-07-29 18:28:20
【问题描述】:

这是我的数据集。


print(data)

          Month.2020        Jan     Feb   Mar      Apr   May     Jun      Jul
1   1st of Month Count     4248   4413    4534    4634   4621   4424    3323
2   Monthly Difference      NA     +165   +121    +100   -13    -197    -1101
3   Monthly Percent Change  NA     0.038  0.027   0.022  -0.002 -0.043  -0.249

我希望我的输出是

          Month.2020        Jan     Feb   Mar      Apr   May     Jun      Jul
1   1st of Month Count     4248   4413    4534    4634   4621   4424    3323
2   Monthly Difference      NA     +165   +121    +100   -13    -197    -1101
3   Monthly Percent Change  NA     3.8%   2.7%    2.2%   -0.2%  -4.3%   -24.9%

我尝试了以下方法,但没有成功

data[3,2:8] <- apply(data[5:7,2:5]*100, 2, function(x) paste0(x, "%"))

我尝试指定每个“单元格”,但也没有用

data[3,3] <- paste("3.8%")

【问题讨论】:

  • data[3:,3:8]&lt;- sprintf("%0.2f",unlist(data[3,3:8])*100)

标签: r dplyr


【解决方案1】:

试试这个:

df[3,-c(1,2)] <- paste0(100*df[3,-c(1,2)],'%')

            Month.2020  Jan  Feb  Mar  Apr   May   Jun    Jul
1      1stofMonthCount 4248 4413 4534 4634  4621  4424   3323
2    MonthlyDifference   NA  165  121  100   -13  -197  -1101
3 MonthlyPercentChange   NA 3.8% 2.7% 2.2% -0.2% -4.3% -24.9%

#Data
df <- structure(list(Month.2020 = c("1stofMonthCount", "MonthlyDifference", 
"MonthlyPercentChange"), Jan = c(4248L, NA, NA), Feb = c(4413, 
165, 0.038), Mar = c(4534, 121, 0.027), Apr = c(4634, 100, 0.022
), May = c(4621, -13, -0.002), Jun = c(4424, -197, -0.043), Jul = c(3323, 
-1101, -0.249)), row.names = c(NA, -3L), class = "data.frame")

【讨论】:

  • 我收到了这个错误; FUN 中的错误(左,右):二进制运算符的非数字参数此外:警告消息:1:在 Ops.factor(左,右)中:'' 对因子 2:在 Ops.factor( left, right) : '' 对于因素 3 没有意义:在 Ops.factor(left, right) 中:'' 对于因素 4 没有意义:在 Ops.factor(left, right) 中:'' 对因素 5 没有意义:在 Ops.factor(left, right) 中:'' 对因素 6 没有意义:在 Ops.factor(left, right) 中:'' 对因素没有意义因素
  • @FruityPebblePug 嗨,我已经添加了我使用的数据。看起来你的一些变量是因素。尝试使用与 df 类似的结构并带有数字列,否则会出错。您的原始数据框中还有其他变量吗?除了这里发布的那些
【解决方案2】:

你可以使用:

df[3, 2:8] <- sapply(df[3, 2:8], function(x) scales::percent(x, big.mark = 1, accuracy = 0.1))

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多