在R中创建条件列

时间:2011-09-02 22:36:34

标签: r

我要在以下数据框OPop中创建两列(WPopData):

OState  OCounty WState  WCounty OYear
AL  Autauga AL  Baldwin 2004
AL  Barbour AL  Bibb    2001
CA  Amador  WY  Weston  1985
CA  Alameda CA  Amador  1999

OPopWPop的值基于四列(Pop1980Pop1990Pop2000Pop2010的值)另一个数据帧Data1

State   County  Pop1980 Pop1990 Pop2000 Pop2010
AL  Autauga 32259   34222   43671   54571
AL  Baldwin 78556   98280   140415  182265
AK  Aleutians East  7768    2464    2697    3141
AK  Aleutians West  NA  9478    5465    5561
CA  Alameda 1105379 1279182 1443741 1510271
CA  Alpine  1097    1113    1208    1175
CA  Amador  19314   30039   35100   38091
CA  Butte   143851  182120  203171  220000
WY  Uinta   13021   18705   19742   21118
WY  Washakie    9496    8388    8289    8533
WY  Weston  7106    6518    6644    7208



Data$OPop <- ifelse(test = Data$OState == Data1$State & Data$OCounty == Data1$County &
                       Data$OYear >= 1980 & Data$OYear < 1990,
                yes = Data1$Pop1980,
                no = ifelse(test = Data$OState == Data1$State & Data$OCounty == Data1$County &
                                   Data$OYear >= 1990 & Data$OYear < 2000,
                             yes = Data1$Pop1990,
                             no = ifelse(test = Data$OState == Data1$State & Data$OCounty == Data1$County &
                                                Data$OYear >= 2000 & Data$OYear < 2010,
                                         yes = Data1$Pop2000,
                                         no = ifelse(test = Data$OState == Data1$State & Data$OCounty == Data1$County &
                                                            Data$OYear >= 2010 & Data$OYear < 2011,
                                                     yes = Data1$Pop2010,
                                                     no = NA))))

任何帮助都将受到高度赞赏。感谢

修改

我收到以下错误消息:

Error in Ops.factor(Data$OState, Data1$State) : 
  level sets of factors are different
In addition: Warning message:
In is.na(e1) | is.na(e2) :
  longer object length is not a multiple of shorter object length

1 个答案:

答案 0 :(得分:5)

我将向您展示合并可以做什么。如果这不是你想要的,那么使用自然语言而不是复杂的代码来解释你想要的东西。 “O”和“W”并不足以确定您的目标。假设这些是两个data.frames:“dat1”,“dat2”(从中删除了无关且长度不足的行:

    >  merge(dat2, dat1, 1:2)
  State  County Pop1980 Pop1990 Pop2000 Pop2010 WState WCounty OYear
1    AL Autauga   32259   34222   43671   54571     AL Baldwin  2004
2    CA Alameda 1105379 1279182 1443741 1510271     CA  Amador  1999
3    CA  Amador   19314   30039   35100   38091     WY  Weston  1985