2016-03-15 80 views
1

我有一个纵向数据集,在这个数据集中人们在不同年份的时间是40,我需要对40岁的人进行分析(倾向评分匹配)。我想创建一个收入变量,该值将在1998年变为四十岁的人中使用Income 1992,在2000年变为四十岁的人中使用Income 1994等等。在R中通过条件命令创建变量

我的数据是这样的(我想Incomenew看起来像这样):

ID | SourceYear| Income1992| Income1994 | Incomenew | 
|---------------|------------|------------|   | 
| 1 | 1998  | 10000  | 12000  | 10000  | 
| 2 | 2000  | 20000  | 15000  | 15000  | 
| 3 | 1998  | 17000  | 16000  | 17000  | 
| 4 | 2000  | 18000  | 20000  | 20000  | 

我很感兴趣,他们的收入,他们转6年前40.我已经调整了购买力的所有收入变量一定year.I的尝试这样做:

Incomenew<-NA 
Incomenew[SourceYear=="1998"]<-Income1992[SourceYear=="1998"] 
Incomenew[SourceYear=="2000"]<-Income1994[SourceYear=="2000"] 

我得到的所有NAS

我也试过这样:

`Incomenew<-if (SourceYear=="1998")] {Income1992} 
        else if (SourceYear==2000) 
       {Income1994}` 

我收到以下错误

错误,如果(SourceYear == “1998年”){:参数是长度为零

这将是很大的帮助,如果有人能够帮助有了这个,我真的很感激它。

+0

您需要显示一个可重复的示例。此外,“收入新”只有长度1,而SourceYear的长度可能不同。尝试'Incomenew < - rep(NA,length(SourceYear))' – akrun

+0

除非'SourceYear'保存为对子集化有用的对象(我无法分辨没有数据),否则它可能需要以数据集为前缀: Income1992 [Income1992 $ SourceYear == 1998,]'。请注意,您还需要在它后面加一个逗号,以指定您的子集年份,并且需要所有列,并确定您的年份是字符串('“1998”')还是数字('2000')。 – alistaire

+0

@akrun非常感谢您的回答,同时尝试创建一个可重复的示例,我发现此命令有效;但在我的原始数据中,它并没有在第一次。然后我意识到这是因为我在SourceYear中有一些NA。当我省略这些时,它就起作用了。谢谢! –

回答

1

在我的原始数据集中,我对SourceYear有一些NA。我没有意识到这个命令很重要。 如果使用SourceYear中没有NA的子集,则第一个命令实际上起作用。一个示例是:

ID<-c(1,2,3,4,5,6) 
SourceYear<-c("1998", "2000", "1998","2002","2000", "2002", NA) 
Income92<-c(100000,120000,170000,180000, 190000, NA) 
Income94<-c(120000,150000,160000,20000,NA, 120000) 
Income96<-c(130000, 110000,NA, 180000, 190000, 180000) 
incomedata<-data.frame(ID, SourceYear,Income92, Income94, Income96, Incomenew) 
summary(incomedata) 
incomedata1<-subset(incomedata, !is.na(incomedata$SourceYear)) 
incomedata1$Incomenew<-rep(NA, length(incomedata1$SourceYear)) 
incomedata1$Incomenew[incomedata1$SourceYear=="1998"]<- 
incomedata1$Income92[incomedata1$SourceYear=="1998"] 
incomedata1$Incomenew[incomedata1$SourceYear=="2000"]<- 
incomedata1$Income94[incomedata1$SourceYear=="2000"] 
incomedata1$Incomenew[incomedata1$SourceYear=="2002"]<- 
incomedata1$Income96[SourceYear=="2002"]