Home > Software engineering >  how to switch values in data frame using two power-based octaves in r
how to switch values in data frame using two power-based octaves in r

Time:11-15

I have a data.frame contains only numerical variables (see below). I want to change the values based on two power-based octaves, i.e., "0 = 0; 1 = 1; 2:3 = 2; 4:7 = 3; 8:15 = 4; 16:31 = 5; 32:63 = 6; 64:127 = 7; else = 8"

Input:

#   V1    V2     V3
#1  0     900    3
#2  1     5      44
#3  3     2      55
#4  7     0      23
#5  15    33     399
#6  28    234    34
#7  99    100    61
#8  140   22     3
#9  190   9      0

Expected Output:

#   V1    V2     V3
#1  0     8      2
#2  1     3      6
#3  2     2      6
#4  3     0      5
#5  4     6      8
#6  5     8      6
#7  7     7      6
#8  8     5      2
#9  8     4      0

I tried the recode() function, but it can not apply to data.frame?

CodePudding user response:

I cannot know how did you try with recode, but this way using apply(df, 1:2, fun) may helps.

Data

dummy <- read.table(text= "   V1    V2     V3
 0     900    3
 1     5      44
 3     2      55
 7     0      23
 15    33     399
 28    234    34
 99    100    61
 140   22     3
 190   9      0", header = T)

Code

poww <- function(x) {
  if (x <= 0){
    0
  } else if (x < 128) {
    floor(log(x, base = 2)) 1
  } else {
    8
  }
}

apply(dummy, 1:2, poww)

      V1 V2 V3
 [1,]  0  8  2
 [2,]  1  3  6
 [3,]  2  2  6
 [4,]  3  0  5
 [5,]  4  6  8
 [6,]  5  8  6
 [7,]  7  7  6
 [8,]  8  5  2
 [9,]  8  4  0

Using lapply and cut

as.data.frame(sapply(dummy, function(x)cut(x, 
                                        breaks = c(-0.5, 0.5, 1.5, 5.5, 10.5, 20.5, 50.5,Inf), 
                                        labels = c(0, 1, 2, 3, 4,5,6)))
)

  V1 V2 V3
1  0  6  2
2  1  2  5
3  2  2  6
4  3  0  5
5  4  5  6
6  5  6  5
7  6  6  6
8  6  5  2
9  6  3  0

CodePudding user response:

Please test the function replace_fun carefully to see if the output is as expected.

replace_fun <- function(x, base = 2){
  # Take log on x   1
  x2 <- log(x   1, base = base)
  # Take the celing
  x3 <- ceiling(x2)
  # Replace number >= 8 to be 8
  x3[x3 >= 8] <- 8
  return(x3)
}

replace_fun(dat)
#   V1 V2 V3
# 1  0  8  2
# 2  1  3  6
# 3  2  2  6
# 4  3  0  5
# 5  4  6  8
# 6  5  8  6
# 7  7  7  6
# 8  8  5  2
# 9  8  4  0

DATA

dat <- read.table(text = "   V1    V2     V3
1  0     900    3
2  1     5      44
3  3     2      55
4  7     0      23
5  15    33     399
6  28    234    34
7  99    100    61
8  140   22     3
9  190   9      0", 
                  header = TRUE)
  •  Tags:  
  • r
  • Related