0

I have ranked rows in a data frame based on values in each column.Ranking 1-10. not every column in picture

I have code that replaces values to NA or 1. But I can't figure out how to replace range of numbers, e.g. 3-6 with 1 and then replace the rest (1-2 and 7-10) with NA.

lag.rank <- as.matrix(lag.rank)
lag.rank[lag.rank > n] <- NA
lag.rank[lag.rank <= n] <- 1

At the moment it only replaces numbers above or under n. Any suggestions? I figure it should be fairly simple?

SEA-Hack
  • 9
  • 1
  • 3
  • 2
    Please paste in actual data (often from `dput` or code to generate the data structure), not a picture of it. Especially when the data in the picture is to be used as input to your data, you are asking us to transcribe your picture. See here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – r2evans Mar 14 '18 at 07:21

2 Answers2

3

Is this what your are trying to accomplish?

> x <- sample(1:10,20, TRUE)
> x
 [1] 1 2 8 2 6 4 9 1 4 8 6 1 2 5 8 6 9 4 7 6
> x <- ifelse(x %in% c(3:6), 1, NA)
> x
 [1] NA NA NA NA  1  1 NA NA  1 NA  1 NA NA  1 NA  1 NA  1 NA  1
Lennyy
  • 5,932
  • 2
  • 10
  • 23
  • 1
    The `c()` is unnecessary, `x <- ifelse(x %in% 3:6, 1, NA)` works just fine. – Kevin Arseneau Mar 14 '18 at 07:21
  • Thanks! This was the tip I needed. I had to modify it a bit, since it also chnaged the dates. This works now perfectly lag.rank[lag.rank <3] <- NA lag.rank[lag.rank >6] <- NA lag.rank[lag.rank %in% 3:6] <- 1 – SEA-Hack Mar 14 '18 at 08:52
1

If your data aren't integers but numeric you can use between from the dplyr package:

x <- ifelse(between(x,3,6), 1, NA)
TTR
  • 129
  • 5