Creating Conditional Columns in R
I've to create two columns (OPop
and WPop
) in the following dataframe Data
:
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
The values of OPop
and WPop
are based on the values of the four columns (Pop1980
, Pop1990
, Pop2000
and Pop2010
) of another dataframe 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 12791开发者_StackOverflow社区82 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))))
Any help will be highly appreciated. Thanks
EDIT
I got the following error message:
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
I am going to show you what merge can do. If this is not what you wanted then USE NATURAL LANGUAGE rather than convoluted code) to explain what you want. "O" and "W" are not sufficient hints to determine your goal. Assume these are two data.frames: "dat1", "dat2" (from which you have removed the extraneous and length-deficient row:
> 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
精彩评论