使用循环创建变量或在r中应用 [英] creating variables using loop or apply in r

查看:173
本文介绍了使用循环创建变量或在r中应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  comp1990< -ifelse( year_begin <1990& year_end> 1990,1,0)

comp1991< -ifelse(year_begin< 1991& year_end> 1991,1,0)

comp1992< ifelse(year_begin< 1992& year_end> 1992,1,0)

1970 - 2007年现在,我只是每一年都有一条线。



在stata中,我可以这样做:

  forvalues n = 1970(1)2007 {

gen comp \`n'==(year_begin< \`n'& year_end> \`n')

}

直接在 R 中执行此操作的方法?我知道对于循环并不好。也许使用apply?



我实质上做的是创建一个虚拟= 1,如果一个银行分行在第n年存在,否则为0(所以如果银行分行成立在n年之前,如果在n年之后关闭,这意味着它在n年运营。 b

解决方案

试试: > sapply(1970:函数(x){ifelse(year_begin< x& year_end> x,1,0)})


I'm trying to create a series of variables in R based on an ifelse function:

comp1990<-ifelse(year_begin<1990 & year_end>1990,1,0)

comp1991<-ifelse(year_begin<1991 & year_end>1991,1,0)

comp1992<-ifelse(year_begin<1992 & year_end>1992,1,0)

I'm doing this for years 1970-2007. Right now, I just have a line for every single year.

In stata, I could do this in the following way:

forvalues n=1970(1)2007 {

gen comp\`n'== (year_begin<\`n' & year_end>\`n')

}

Is there a similarly straightforward way to do this in R? I know for loops aren't great. Maybe using apply?

What I'm essentially doing is creating a dummy = 1 if a bank branch exists in year n and 0 otherwise (so if the bank branch was established before year n and if it closed after year n), which means it was operating in year n.

Thanks in advance for the help!

解决方案

Try:

 sapply(1970:2007,function(x){ ifelse(year_begin<x & year_end>x,1,0) })

这篇关于使用循环创建变量或在r中应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆