1

Hi I have a similar question to [text] (Replace values in data frame from column of indexes) I have a data frame that looks like the following.

COL1 <- c(1,1,1,NA,1,1)
COL2 <- c(1,NA,NA,1,1,1)
COL3 <- c(1,1,1,1,1,1)
index <- c(2,3,2,3,2,2)
Data <- data.frame (COL1, COL2, COL3, index)
Data
COL1 COL2 COL3 index
1    1    1    2
1    NA   1    3
1    NA   1    2
NA   1    1    3
1    1    1    2
1    1    1    2

Where "index" tells me a certain threshold. For each row I would like to replace all column values up to the value indicated by "index" with a unique value like 99. So I would end up with something like

COL1 COL2 COL3
99   99   1
99   99   99
99   99   1
99   99   99
99   99   1
99   99   1

From the previous question the answer to change the instances after the "index" would be

t(apply(Data, 1, function(x) {
  i1 <- match( x[4], names(x)[-4])+1
  i1[i1>3] <- 0
  i1 <- if(i1!=0) i1:3 else i1
  c(replace(x[-4], i1, 99), x[4])}))

However this throws me errors

"Error in if (i1 != 0) i1:3 else i1 : missing value where TRUE/FALSE needed"

A. Suliman
  • 12,923
  • 5
  • 24
  • 37

2 Answers2

3

Heere is one option with apply where we loop through the rows (MARGIN = 1), replace the values of each row by creating a condition based on the 4th value column and assign it to 99

t( apply(Data, 1, function(x) replace(x, seq_along(x) <= x[4], 99)))[,-4]
#     COL1 COL2 COL3
#[1,]   99   99    1
#[2,]   99   99   99
#[3,]   99   99    1
#[4,]   99   99   99
#[5,]   99   99    1
#[6,]   99   99    1

Or with vectorized approach, by creating a logical matrix based on the col index and the 'index' column of 'Data' to replace the values of the first 3 columns with 99

replace(Data[1:3], col(Data[1:3]) <= Data$index, 99)
#  COL1 COL2 COL3
#1   99   99    1
#2   99   99   99
#3   99   99    1
#4   99   99   99
#5   99   99    1
#6   99   99    1
akrun
  • 874,273
  • 37
  • 540
  • 662
2
replace(Data, cbind(rep(1:NROW(Data), Data$index), sequence(Data$index)), 99)
#  COL1 COL2 COL3 index
#1   99   99    1     2
#2   99   99   99     3
#3   99   99    1     2
#4   99   99   99     3
#5   99   99    1     2
#6   99   99    1     2
d.b
  • 32,245
  • 6
  • 36
  • 77