R 如何根据特定分类进行计算?
我试图使我的计算依赖于我给出的各种观察结果的分类 我的数据示例如下所示:R 如何根据特定分类进行计算?,r,criteria,R,Criteria,我试图使我的计算依赖于我给出的各种观察结果的分类 我的数据示例如下所示: 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
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
我如何在计算中加入这样的标准
谢谢 您可以像下面这样尝试
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))
您可以像下面这样尝试
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))
哈,这真是天才!哈,这真是天才!