Runif在一列上但行之间的数据类型不同

时间:2018-01-31 19:20:13

标签: r

我目前正在生成一个数据框 -

modelOption_RT <- data.frame(
  typeID = rep(c(2,1), each = 4),
  ID = c(1:8),
  modelOption = c("good", "avg", "bad", "marginCost", "year1Premium")[c(1,2,3,4,5,1,2,3)],
  descrip = c("Favorable", "Average", "Adverse", "Margin Cost", "Year 1 Premium")[c(1,2,3,4,5,1,2,3)],

  # Generate random values for model options
  vals = sort(
      round(
      runif(5, min=0, max=1),
      digits = 2
      ), decreasing = TRUE)[c(1,2,3,4,5,1,2,3)]
    )

> modelOption_RT
  typeID ID  modelOption        descrip vals
1      2  1         good      Favorable 0.61
2      2  2          avg        Average 0.36
3      2  3          bad        Adverse 0.24
4      2  4   marginCost    Margin Cost 0.11
5      1  5 year1Premium Year 1 Premium 0.01
6      1  6         good      Favorable 0.61
7      1  7          avg        Average 0.36
8      1  8          bad        Adverse 0.24

这只有一个问题 - 当前val列中的所有值都代表一个百分比,但是:

  • year1Premium的 vals 列应为货币,因此0到100000000之间的任何值

有什么建议吗?我唯一的想法是按原样创建数据框,并手动更改数据框函数外的year1Premium的val值。不确定它是否有效。

modelOption_RT[modelOption_RT$modelOption == "year1Premium", "vals"] <- runif(1, min=0, max=10000)

1 个答案:

答案 0 :(得分:1)

您可以使用dplyr&#39; mutate()replace()

set.seed(96311)

library(dplyr)
modelOption_RT <- data.frame(
  typeID = rep(1:2, each = 4),
  ID = 1:8,
  modelOption = c("good", "avg", "bad", "marginCost", 
                  "year1Premium")[c(1:5, 1:3)],
  descrip = c("Favorable", "Average", "Adverse", "Margin Cost", 
              "Year 1 Premium")[c(1:5, 1:3)],
  vals = sort(round(runif(8, min=0, max=1), digits = 2), decreasing = TRUE)) %>%
  mutate(vals = replace(vals, modelOption == "year1Premium", 
                        runif(1, min=0, max=10000)))

modelOption_RT
# typeID ID  modelOption        descrip    vals
# 1      1  1         good      Favorable    0.95
# 2      1  2          avg        Average    0.66
# 3      1  3          bad        Adverse    0.56
# 4      1  4   marginCost    Margin Cost    0.49
# 5      2  5 year1Premium Year 1 Premium 6032.65
# 6      2  6         good      Favorable    0.32
# 7      2  7          avg        Average    0.17
# 8      2  8          bad        Adverse    0.03