How do you combine columns with conditions in R? -


i have data frame looks in r:

d = data.frame(countrycode = c(2, 2, 2, 3, 3, 3),        year = c(1980, 1991, 2013, 1980, 1991, 2013),        pop90 = c(1, 1, 1, 2, 2, 2),        pop00 = c(3, 3, 3, 4, 4, 4),        pop10 = c(5, 5, 5, 6, 6, 6)) 

desired output:

res = data.frame(countrycode = c(2, 2, 2, 3, 3, 3),        year = c(1980, 1991, 2013, 1980, 1991, 2013),        popcombined = c(1, 3, 5, 2, 4, 6)) 

i combine pop90, pop00 , pop10 1 column years 1980-1990 reflect value of pop90, years 1991-2000 reflect value of pop00 , years 2001-2013 reflect value of pop10. how can this? have tried merge function not set years in place reflect conditions set out above.

you can use row/col indexing

popcombined <- d[3:5][cbind(1:nrow(d),findinterval(d$year,               c(-inf, 1990, 2000, inf)))]  cbind(d[1:2], popcombined) #    countrycode year popcombined #1           2 1980           1 #2           2 1991           3 #3           2 2013           5 #4           3 1980           2 #5           3 1991           4 #6           3 2013           6 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -