D. Chamberlin
D. Chamberlin

Reputation: 75

Increment by 0.1 for every change in column in R

Using this data frame I would like to increase var2 by 0.1 for each change in var1

df <- data.frame(var1=c("a", "a", "1", "0", "b", "b", "b", "c", "1", "1"))

in this case the result should be:

var1 var2
   a    1
   a    1
   1    1.1
   0    1.2
   b    1.3
   b    1.3
   b    1.3
   c    1.4
   1    1.5
   1    1.5

I was able to use the following code to increase var2 by 1 for each change in var1 but I could not manipulate this to increase by 0.1.

df$var2 <- c(0,cumsum(as.numeric(with(df,var1[1:(length(var1)-1)] != var1[2:length(var1)]))))

Upvotes: 1

Views: 1665

Answers (2)

Shahar Bental
Shahar Bental

Reputation: 1001

You can split this task into smaller tasks, and complete them in order.

  1. Create a column which is "lagging" in one row
  2. Compare the 2 columns
  3. Calculate the cumulative sum, put it in the dataframe

So in code:

helper = c(df$var1[1],df$var1[1:(nrow(df)-1)])

isDifferent = as.integer(df$var1)!=helper note the casting to int due to R creating the strings as factors

df$var2=1+cumsum(isDifferent *0.1)

Upvotes: 1

akrun
akrun

Reputation: 886978

We can try

df$var1 <- as.character(df$var1)
df$var2 <- seq(0, 1, by = 0.1)[with(df, cumsum(c(TRUE, var1[-1]!= var1[-length(var1)])))] + 1

Upvotes: 2

Related Questions