Switch statement throws error - r

I would like to use a switch statement to convert a number. If the case is 1 the number should be 13, case 2 should be 14 etc...
Therefore I wrote the following statement:
settime <- function(time){
switch(time,
"1" = 13,
2 = 14,
3 = 15,
4 = 16,
5 = 17,
6 = 18,
7 = 19,
8 = 20,
9 = 21,
10 = 22,
11 = 23,
12 = 24)
}
This however gives me the following error:
Error: unexpected '=' in: " switch(time,
1 ="
Any thought on where I go wrong?

The more obvious way to get what you want is with time + 12.
It is simpler than switch and allows you to pass a vector and not just a value.
But as your problem might be more complicated than the one you put in your example and if you feel you need to use switch (for which you can pass only one value at a time), and to complete my comment, you have 2 options to do that, as stated in the below sample from help(switch):
switch works in two distinct ways depending whether the first argument
evaluates to a character string or a number.
If the value of EXPR is not a character string it is coerced to
integer. Note that this also happens for factors, with a warning, as
typically the character level is meant. If the integer is between 1
and nargs()-1 then the corresponding element of ... is evaluated and
the result returned: thus if the first argument is 3 then the fourth
argument is evaluated and returned.
If EXPR evaluates to a character string then that string is matched
(exactly) to the names of the elements in .... If there is a match
then that element is evaluated unless it is missing, in which case the
next non-missing element is evaluated, so for example switch("cc", a =
1, cc =, cd =, d = 2) evaluates to 2. If there is more than one match,
the first matching element is used. In the case of no match, if there
is a unnamed element of ... its value is returned. (If there is more
than one such argument an error is returned.)
Either time is a character variable:
time <- "3"
switch(time, "1"=13, "2"=14, "3"=15, "4"=16)
# [1] 15
Or time is numeric:
time <- 3
switch(time, 13, 14, 15, 16)
# [1] 15

We could do this without using any switch. I am not sure how efficient switch will be for large vectors. But, the below method should be fast enough.
res <- setNames(13:24, 1:12)[as.character(v1)]
res
#4 3 9 7 8 12 4 10 10 4 8 5 9 9 4 11 3 1 7 2 2 7 9 2 3 9
#16 15 21 19 20 24 16 22 22 16 20 17 21 21 16 23 15 13 19 14 14 19 21 14 15 21
From the above, it is easier to remove the name.
unname(res)
Or
as.vector(res)
We do not need to use as.character as the elements start from 1:12. But, in case, it is a different vector, then we may need to be extra careful.
data
set.seed(24)
v1 <- sample(1:12, 30, replace=TRUE)

Related

WGCNA : Choosing a soft-threshold power

powers = c(c(1:10), seq(from = 12, to=20, by=2));
While going through WGCNA i came across this code which i am not able to understand, can anybody explain me the meaning of that piece of code
The code will create a vector of numbers stored in powers.
Specifically: 1:10 creates the numbers 1 2 3 4 5 6 7 8 9 10 (can read as 1 through 10) and seq(from = 12, to = 20, by = 2) creates a sequence of every other number from 12 to 20, i.e. 12 14 16 18 20.
Powers will contain the following 15 numbers: 1 2 3 4 5 6 7 8 9 10 12 14 16 18 20
I am not familiar with the WGCNApackage or if powers is an argument to a function, but this is what powers contains.

Changing the length of an object

Alpha is an object of length 10, then
alpha <- alpha[2 * 1:5]
Makes it an object of length 5 consisting of just the former components with even index.
How is this working?
Also when running the code, the entire object contains only NA. Is there anyway of retaining the original values?
I added elements and still it showed NA.
Hard to give a proper answer without knowing the content of alpha and what exactly you're trying to accomplish, but hope this helps.
Squared brackets are used for indexing:
alpha <- seq(10, 50, 10)
> alpha
[1] 10 20 30 40 50
> alpha[2]
[1] 20
If there's nothing in a position (e.g. if that position don't exist in the vector), it will return "Not Available" (NA):
> alpha[6]
[1] NA
> alpha[3:7]
[1] 30 40 50 NA NA
If you want to add new values to the vector, you specify the position(s) and attribute the value(s):
alpha[8:12] <- 8:12
> alpha
[1] 10 20 30 40 50 NA NA 8 9 10 11 12
# the positions with no values atributed are filled with NA
If you want to make an operation in only some positions, you specify the positions and make the operation over it:
> 2*alpha[4:8]
[1] 80 100 NA NA 16
# positions 4, 5, 6, 7, and 8 multiplied by 2
Which is different of using an operation to select positions:
> alpha[2*4:8]
[1] 8 10 12 NA NA
# showing the content of positions 8, 10, 12, 14 and 16

seq_along() - truncating a replication in r

I would like to generate the month number to go along with a list of values. The problem is that the list is not a full 2 replications of 12 months. It is 12 from the first year and 10 from the second year.
tibble(value=rnorm(22))
Some things I have tried are rep(1:12,2), thinking that the sequence would stop
when it hit the end of the length of the dataframe. I also tried seq_along(along.with=value,1:12) with the same line of thinking.
You want the length.out argument to rep():
rep(1:12, length.out = 22)
which gives
> rep(1:12, length.out = 22)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10
We get this because, from ?rep:
‘length.out’ may be given in place of ‘times’, in which case ‘x’
is repeated as many times as is necessary to create a vector of
this length. If both are given, ‘length.out’ takes priority and
‘times’ is ignored.
I would roll out 22 months and then use a modulo operator to get months in subsequent year(s)
library(dplyr)
tibble(value=rnorm(22)) %>%
mutate(month=1:22,
month=ifelse(month%%12==0, 12, month%%12)

What type returns table in R?

I wrote this lines of code below.
I want to get the most frequent value in matrix:
matrix7 <- matrix(sample(1:36, 100, replace = TRUE), nrow = 1)
t <- table(matrix7)
print(t)
a <- which.max(table(matrix7))
print(unlist(a))
it prints this:
> matrix7 <- matrix(sample(1:36, 100, replace = TRUE), nrow = 1)
> t <- table(matrix7)
> print(t)
matrix7
1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 25 26 27 28 29 30 31 32 34 35 36
4 5 1 5 2 5 1 3 1 4 2 2 2 5 5 1 3 7 2 3 2 3 2 1 4 4 2 2 2 5 2 5 3
> a <- which.max(table(matrix7))
> print(unlist(a))
19
18
>
What type is my t variable and a variable,
and how can I get the most frequent value from matrix?
To know the "type" of variable use:
class(t)
class(a)
But notice you are already setting your matrix7 as table here: t <- table(matrix7) while your variable a is an integer.
To get the most common element on your variable (t in your case):
sort(table(as.vector(t)))
In general, if you want to know the "type" (more properly called the class) of an object, use the function class:
> class(t)
[1] "table"
There are a few ways you can find the most frequent value. Given that you have already calculated the which.max, you can take the corresponding name of t:
> as.numeric(names(t)[a])
[1] 5 ## I have a different random number seed to you :)
Note that you can't just take t[a] since that might return an integer code (factors are integers underneath, and the integer might not be what you expect).
In your example, the object a is an integer vector of length one. The "data" is 18, and it has the "name" 19. Hence another and perhaps simpler way to get the most frequent value is to take names(a).
You can either use class() to get the the class attribute of an R object or typeof() to get the type or storage mode.
Class and type of a are 'integer', the class of t is 'table' and the type is 'integer'.
Note that a is a named integer, this is why 2 values are printed. If you use names(a) it will only return the value (as a character) of a.
If you use which.max(tabulate(matrix7)) it will return the value without the need to change it further.
which.max(tabulate(matrix7))
[1] 16
(Side node: since no seed is in your code the result differs, you can set it using set.seed(x) where x is an integer).

How do I repeat only a part of a vector?

I have a vector of: 0,24,12,12,12,96,12,12,12,12,12,12.
I want to repeat only a part of it from 96 to the last element (12). The first part (0, 24, 12, 12, 12) I want to keep constant.
Could you please help ?
The answer depends on whether number 96 is always located at the 6th position inside your vector. If so, please refer to the first comment underneath your question. If the position is variable, however, you could implement a simple query that identifies the position of 96 inside your vector, and then repeat the part of the vector starting from there as often as you wish (2 times in the below-mentioned code).
x <- c(0,24,12,12,12,96,12,12,12,12,12,12)
# Identify index of 96
id <- which(x == 96)
# Repeat part of vector starting from `id` 2 times
c(x[1:(id-1)], rep(x[id:length(x)], 2))
# # Which results in
# [1] 0 24 12 12 12 96 12 12 12 12 12 12 96 12 12 12 12 12 12

Resources