Home > Mobile >  How to replace whole numbers within a list with infinity in R programming
How to replace whole numbers within a list with infinity in R programming

Time:10-21

Within the object that is saved as the first element of Question3_Object, replace the whole numbers (i.e., numbers without fractions) with infinity.

  1. What arithmetic function to use to identify a set of integers (whole numbers) from the object . And how do i replace it as the question asked.
structure(Question3_Object)
List of 3
  : num [1:7] -3 0.333 3.667 7 10.333 ...
  : num [1:21] -3 -2 -1 0 1 2 3 4 5 6 ...
  :List of 3
  ..$ : num [1:6] 3 2.1 3.3 4 1.5 4.9
  ..$ : chr [1:6] "LOW" "MED" "LOW" "MED" ...
  ..$ : logi [1:9] FALSE TRUE TRUE TRUE FALSE TRUE ...```

CodePudding user response:

You can check if the element is an integer with x == round(x). and if it is, replace it with Inf

CodePudding user response:

You can use %% to replace the integer values in the first element of Question3_Object as follows:

Question3_Object[[1]][Question3_Object[[1]]%%1==0] <- Inf

CodePudding user response:

You can do

Question3_Object[[1]][Question3_Object[[1]] %% 1 == 0] <- Inf

Which results in

str(Question3_Object)
#> List of 3
#>  $ : num [1:7] Inf 0.333 3.667 Inf 10.333 ...
#>  $ : num [1:21] -3 -2 -1 0 1 2 3 4 5 6 ...
#>  $ :List of 3
#>   ..$ : num [1:6] 3 2.1 3.3 4 1.5 4.9
#>   ..$ : chr [1:6] "LOW" "MED" "LOW" "MED" ...
#>   ..$ : logi [1:9] FALSE TRUE TRUE TRUE FALSE TRUE ...

Data inferred from question in reproducible form

Question3_Object <- list(seq(-3, 17, 10/3), 
                         1:21 - 4,
                         list(c(3, 2.1, 3.3, 4, 1.5, 4.9),
                              c("LOW", "MED", "LOW", "MED", "LOW", "MED"),
                              1 == c(0, 1, 1, 1, 0, 1, 1, 0, 0)))

str(Question3_Object)
#> List of 3
#>  $ : num [1:7] -3 0.333 3.667 7 10.333 ...
#>  $ : num [1:21] -3 -2 -1 0 1 2 3 4 5 6 ...
#>  $ :List of 3
#>   ..$ : num [1:6] 3 2.1 3.3 4 1.5 4.9
#>   ..$ : chr [1:6] "LOW" "MED" "LOW" "MED" ...
#>   ..$ : logi [1:9] FALSE TRUE TRUE TRUE FALSE TRUE ...

Created on 2022-10-20 with reprex v2.0.2

  • Related