我有一个纵向数据集,人们在不同的年份中都是40岁,我需要对40岁的人做一个分析(倾向分数匹配)。我想创建一个收入变量,用于1998年年满40岁的人使用Income 1992,对2000年年满40岁的人使用Income 1994等等。
我的数据看起来像这样(我希望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 | 我对他们40岁前6年的收入很感兴趣。我已经根据某一年的购买力调整了所有收入变量,我试了一下:
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}`我得到以下错误
if (SourceYear== "1998")中的错误{:参数长度为零
如果有人能帮上忙,我会很感激的。
发布于 2016-03-26 20:04:14
在我的原始数据集中,我有一些用于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"]https://stackoverflow.com/questions/36004384
复制相似问题