问题描述
我在R中有以下数据表:
find(line=>line[keyFieldName]==keyFieldValue): { ...state['lines'].find(line=>line[keyFieldName]==keyFieldValue),
还有47个行业。
现在,我想为某些行业和年份创建一个虚拟变量,但是我正在努力制定if语句。如果为true,则虚拟对象应打印1,否则为空(或者为0)。但是,我不想用重复的代码覆盖以前的语句。
compustat.medians $ industry是 factor 类的 compustat.medians $ fyear是整数
类我尝试了以下语法:
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
我得到一个错误:条件的长度> 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))