Set values ​​that exceed the index for NA, for each row

In R, I have a matrix dfand vector invalidAfterIndex. For the iith row, I would like to set the invalidAfterIndex[i]value for all elements with index greater NA. For instance:

> df <- data.frame(matrix(rnorm(20), nrow=5))
> df
            X1         X2         X3          X4
1  2.124042819 -0.2862224  0.1686977  2.14838198
2  0.777763004  0.2949123 -0.4331421 -0.81278586
3 -0.003226624 -0.2326152 -1.5779695 -1.23193913
4  0.165975919 -0.1879981 -0.8214994 -1.40267202
5  1.299195865 -0.9418217 -1.5302512  0.03164781
> invalidAfterIndex <- c(2,3,1,4,1)

I would like to:

            X1         X2         X3          X4
1  2.124042819 -0.2862224  NA         NA
2  0.777763004  0.2949123 -0.4331421  NA
3 -0.003226624  NA         NA         NA
4  0.165975919 -0.1879981 -0.8214994 -1.40267202
5  1.299195865  NA         NA         NA

How can I do this without a for loop?

+4
source share
2 answers

You can do

is.na(df) <- col(df) > invalidAfterIndex

Or as @digEmAll suggested

df[col(df) > invalidAfterIndex] <- NA
+6
source

Here is the option c Map, with which you can pass the position of the column and column to a function in which you can replace the elements with an index superior to invalidAfterIndex, with NA:

df[] <- Map(function(col, index) replace(col, index > invalidAfterIndex, NA), df, seq_along(df))

df
#            X1         X2         X3        X4
#1  2.124042819 -0.2862224         NA        NA
#2  0.777763004  0.2949123 -0.4331421        NA
#3 -0.003226624         NA         NA        NA
#4  0.165975919 -0.1879981 -0.8214994 -1.402672
#5  1.299195865         NA         NA        NA
0
source

Source: https://habr.com/ru/post/1669303/


All Articles