Home > Net >  Is there r functions to sort these data out in R?
Is there r functions to sort these data out in R?

Time:03-31

Here is a small sample of my data:

dat<-read.table (text=" ID  A   S   T   R1  R2  R3
1   10  21  80  60  80  44
2   15  14  90  70  76  40
3   22  10  20  90  55  33
", header=TRUE)

Column A searches in column S to find the nearest number. ID1 Corespondes to R1, ID2 coresponds to R2 and ID3 corespondes to R3. When the number is funded in S, the corresponding R-value to ID is selected. For example, in ID2, the nearest value in the S is 14 for 15, so 76 in R2 is selected. The outcome table is as follow:

ID  A   S   T   out
1   10  21  80  44
2   15  14  90  76
3   22  10  20  90

CodePudding user response:

In base R you could do:

rows    <- apply(outer(dat$A, dat$S, function(a, b) abs(a - b)), 1, which.min)
cols    <-  grep("R\\d ", names(dat))
indices <- cbind(rows, cols)
cbind(dat[1:4], out = dat[indices])

CodePudding user response:

A dplyr purrr option could be:

dat %>%
    mutate(out = paste0("R", map_chr(A, ~ which.min(abs(.x - S))))) %>%
    rowwise() %>%
    mutate(out = get(out))

     ID     A     S     T    R1    R2    R3   out
  <int> <int> <int> <int> <int> <int> <int> <int>
1     1    10    21    80    60    80    44    44
2     2    15    14    90    70    76    40    76
3     3    22    10    20    90    55    33    90

CodePudding user response:

Very similar to a solution already presented but without rowwise

dat %>%
  mutate(idx = map_int(A, ~ which.min(abs(.x - S)))) %>%
  mutate(., out = select(., R1:R3)[cbind(row_number(), idx)]) |>
  select(-idx, -c(R1:R3))

##>   ID  A  S  T out
##> 1  1 10 21 80  44
##> 2  2 15 14 90  76
##> 3  3 22 10 20  90
  •  Tags:  
  • r
  • Related