Re: [R] Capturing positive and negative changes using R

2019-07-21 Thread Faradj Koliev
Thank you much, this was very helpful. Jim’s and Daniel’s code was spot on. Indeed, as Jeff Newmiller pointed out, one of the problems was that I assumed that R could recognise decimals - I did as Richard O’Keefe suggested and the problem was gone. Thanks again! Faradj > On 21 Jul 2019, a

Re: [R] Capturing positive and negative changes using R

2019-07-21 Thread Daniel Nordlund
Here is one more option using the ave() function. Using Jim's data and naming convention fkdf$X1_change <- ave(fkdf[,'X1'], fkdf$Country, FUN=function(x) c(0,diff(x))) fkdf$X2_change <- ave(fkdf[,'X2'], fkdf$Country, FUN=function(x) c(0,diff(x))) hope this is helpful, Dan -- Daniel Nordlun

Re: [R] Capturing positive and negative changes using R

2019-07-20 Thread Richard O'Keefe
If "Fardadj was expecting R to recognise the comma as the decimal" then it might be worth mentioning the 'dec = "."' argument of read.table and its friends. On Sun, 21 Jul 2019 at 12:48, Jeff Newmiller wrote: > It is possible that part of the original problem was that Fardadj was > expecting R

Re: [R] Capturing positive and negative changes using R

2019-07-20 Thread Jeff Newmiller
It is possible that part of the original problem was that Fardadj was expecting R to recognise the comma as the decimal and he read in that column as a factor without realizing it. Factors are discrete, not continuous. He should use the str() function to identify the column types in his data fra

Re: [R] Capturing positive and negative changes using R

2019-07-20 Thread Jim Lemon
Hi Faradj, Rui's advice is correct, here's a way to do it. Note that I have replaced the comma decimal points with full stops for my convenience: fkdf<-read.csv(text="Year,Country,X1,X2 1990,United States,0,0.22 1991,United States,0,0.22 1992,United States,0,0.22 1993,United States,0,0.22 1994,Uni

Re: [R] Capturing positive and negative changes using R

2019-07-20 Thread Rui Barradas
Hello, Please don't post in HTML, the data is unreadable. Two ideas: 1) Why c(FALSE, diff()) if diff returns numeric values? Use c(0, diff) instead, and you won't need the coercion to numeric with the plus sign. 2) There are many ways to group by a variable, in this case 'Country'. See in base

[R] Capturing positive and negative changes using R

2019-07-20 Thread Faradj Koliev
Dear R-users, I have a country-year data for 180 countries from 1970 to 2010. I’m interested in capturing positive and negative changes in some of the variables. Some of these variables are continuous (0,25, 0,33, 1, 1,5 etc) others are ordered (0,1, 2). To do this, I use this code data$X1_c