【问题标题】:How do I make a calculation dependent on a certain classification?如何根据某个分类进行计算?
【发布时间】:2021-04-15 13:15:43
【问题描述】:

我正在尝试根据我给出的各种观察结果来进行计算。

我的数据示例如下所示:

Permno  R&D Industry    Input
1       202    3    
2       414    4    
3       458    5    
4       333    3    
5       294    3    
6       378    5    
7       459    3    
8        69    2    
9       364    1    
10      332    2    
11      112    4    
12      279    1    
13      417    3    
14      454    5    
15      362    5    
16      271    2    
17      252    2    
18      486    5    
19       92    5    
20       99    3    

在我的输入变量中,我想例如有以下计算:

If Industry = 1 then R&D / 2
If Industry = 2 then R&D / 2
If Industry = 3 then R&D / 6
If Industry = 4 then R&D / 8
If Industry = 5 then R&D / 12

如何将标准纳入我的计算中?

谢谢!

【问题讨论】:

    标签: r criteria


    【解决方案1】:

    您可以尝试match,如下所示

    transform(
      df,
      R.D_new = R.D / c(2, 2, 6, 8, 12)[match(Industry, 1:5)]
    )
    

    给了

       Permno R.D Industry    R.D_new
    1       1 202        3  33.666667
    2       2 414        4  51.750000
    3       3 458        5  38.166667
    4       4 333        3  55.500000
    5       5 294        3  49.000000
    6       6 378        5  31.500000
    7       7 459        3  76.500000
    8       8  69        2  34.500000
    9       9 364        1 182.000000
    10     10 332        2 166.000000
    11     11 112        4  14.000000
    12     12 279        1 139.500000
    13     13 417        3  69.500000
    14     14 454        5  37.833333
    15     15 362        5  30.166667
    16     16 271        2 135.500000
    17     17 252        2 126.000000
    18     18 486        5  40.500000
    19     19  92        5   7.666667
    20     20  99        3  16.500000
    

    数据

    > dput(df)
    structure(list(Permno = 1:20, R.D = c(202L, 414L, 458L, 333L, 
    294L, 378L, 459L, 69L, 364L, 332L, 112L, 279L, 417L, 454L, 362L,
    271L, 252L, 486L, 92L, 99L), Industry = c(3L, 4L, 5L, 3L, 3L,
    5L, 3L, 2L, 1L, 2L, 4L, 1L, 3L, 5L, 5L, 2L, 2L, 5L, 5L, 3L)), class = "data.frame", row.names = 
    c(NA,
    -20L))
    

    【讨论】:

    • 哈,这真是天才!
    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 2021-10-28
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多