Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Function to create a data.frame containing manipulated data from another data.frame

Tags:

r

Hi I am new to R and have a question. I have a data.frame (df) containing about 30 different types of statistics from years 1960-2012 for about 100 different countries. Here is an example of what it looks like:

     Country      Statistic.Type     1960      1961      1962      1963 ...  2012 
__________________________________________________________________________________
1    Albania      Death Rate          10        21        13        24        25  
2    Albania      Birth Rate          7         15        6         10        9  
3    Albania      Life Expectancy     8         12        10        7         20  
4    Albania      Population          10        30        27        18        13
5    Brazil       Death Rate          14        20        22        13        18
6    Brazil       Birth Rate          ...  
7    Brazil       Life Expectancy     ...  
8    Brazil       Population          ...  
9    Cambodia     Death Rate          ...  
10   Cambodia     Birth Rate          ...                  etc...

Note that there are 55 columns in total and the values in each of the 53 year columns are made up for the purposes of this question.

I need help writing a function which takes as inputs the country and statistic type and returns a new data.frame with 2 columns which shows the year and value in each year for a given country and statistic type. For example, if I input country=Brazil and statistic.type=Death Rate into the function, the new data.frame should look like:

     Year    Value 
_____________________
1    1960     14
2    1961     20
3    1962     22
...
51   2012     18

I have no idea on how to do this, if anyone can give me any ideas/code/packages to install then that would be very helpful.

Thank you so much!

like image 289
user2397274 Avatar asked Jun 30 '26 11:06

user2397274


1 Answers

If df is your data.frame, all you need is this:

f <- function(country, statistic.type, data=df)
{
 values <- data[data$Country==country & data$Statistic.Type==statistic.type,-(1:2)]

 cbind(Year=names(df)[-(1:2)], Value=values)
}

Use it as

f(country="Brazil", statistic.type="Death Rate")
like image 195
Ferdinand.kraft Avatar answered Jul 02 '26 05:07

Ferdinand.kraft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!