我在R中有以下数据表:
industry fyear change.in.employeegrowth change.in.netincome.to.sales change.in.ROA change.in.Assetturnover change.in.RandD change.in.CAPEX.byassets
1 Agriculture 1999 0.08766928 0.036667693 0.021561014 0.08213972 1.893469e-03 0.014274404
2 Agriculture 2000 0.13963964 0.066484354 0.027813095 0.15047066 4.116929e-03 0.028307019
3 Agriculture 2001 0.13636364 0.041775993 0.030575742 0.05965700 8.678983e-03 0.014702146
4 Agriculture 2002 0.05484111 0.092764170 0.058518761 0.04699455 2.078513e-03 0.010364144
5 Agriculture 2003 0.08757912 0.084572235 0.041094305 0.10765641 4.061465e-03 0.008522656
6 Agriculture 2004 0.04970685 0.058833426 0.028568214 0.02540688 1.275619e-02 0.005628402
7 Agriculture 2005 0.17954545 0.040047709 0.041380006 0.08353320 3.917954e-02 0.009383056
8 Agriculture 2006 0.19047619 0.063405763 0.047080200 0.07955826 2.465875e-02 0.005213245
9 Agriculture 2007 0.09165972 0.098566476 0.064550850 0.09336734 9.296165e-03 0.008958315
10 Agriculture 2008 0.04227658 0.076702017 0.056679238 0.12820537 2.575690e-03 0.010149566
以及另外47个行业。
现在我想为某些行业和年份创建一个虚拟变量,但我正在努力制定我的if语句。如果为true,则虚设应打印1,否则不打印任何内容(或者打印0(。但是,我不想用重复的代码覆盖以前的语句。
compustat.medians$industry属于因子compustat.medians$fyear属于integer
我尝试了以下语法:
compustat.medians$pre.wave.year <-if( (compustat.medians$industry == "Food Products") & (compustat.medians$fyear == 2012) )
or ( (compustat.medians$industry == "Candy and Soda") & (compustat.medians$fyear == 2012) )
or ( (compustat.medians$industry == "Recreation") & (compustat.medians$fyear == 2005) )
{
print(1)
}
我得到错误:条件的长度>1,并且只有第一个元素将用于所有变体,我尝试。
有没有一种方法可以将if语句用于多个条件,并同时使用几种可能的组合?
谢谢,
- 您需要使用
ifelse
而不是if
/else
- R中没有
or
函数,请使用|
- 代替使用
ifelse(condition, 1, 0)
,我们可以使用as.integer(condition)
- 您可以将多个值与
%in%
进行比较,因此可以将条件1和条件2组合起来
尝试:
compustat.medians$pre.wave.year <- as.integer(with(compustat.medians,
industry %in% c("Food Products", "Candy and Soda") & fyear == 2012 |
industry == "Recreation" & fyear == 2005))