Finding two middle values in R? [closed] - r

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
EDIT: the output is : [1] 49 65. Only allowed to use INDEXING. Code cannot be hard coded.
Can anyone please provide the code in R for finding two middle values in a vector with 10 elements?
The code would need to work for any vector size. so it cannot be hardcoded
The elements are 59,46,76,60,49,65,82,68,99,52

x <- c(59,46,76,60,49,65,82,68,99,52)
if(length(x)%%2 == 0) {
x[c(length(x)/2,(length(x)/2+1))]
} else{
x[ceiling(length(x)/2)]
}
[1] 49 65

Lets create a vector array with our values
array <- c(59,46,76,60,49,65,82,68,99,52)
From left to right, the middle two values of this array are the 5th and 6th
array[5:6]
# 49 65
If we want the numerically 5th and 6th highest number we can go with
sort(array)[5:6]
# 60 65
If you want to know which position of the original array the middle two elements are in, you can do
which(array %in% sort(array)[5:6])
# 4 6
You can expand the above programmatically for any array of even length by doing
n <- length(array)
x <- n/2
y <- x + 1
Then in any of the previous three examples, just replace 5 by x and 6 by y.

Like this ?
x <- c(59,46,76,60,49,65,82,68,99,52)
c(x[length(x)/2],x[length(x)/2 + 1])

Related

Matrix solving in R with for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to solve matrix in R.I have 3 matrix like this, Uf[11,3], Uft[3,11] and AT[3,3] .For the first two 11 rows and columns represent 11 different values that I want to use. And at last I need to reach 11 different "D"
values.D = (11/3) * Uft * AT * Uf
but if i try this with for loop I had [11,11] matrix .So here is the problem , how can I get [11,1] or [1,11] matrix to see my D results. I also get this error "subscript out of bounds" when I try this code.
for (i in 1:11) {
print((1/3) * 11 * Uft[[,i]] %*% Uf[[i, ]] %*% AT[[,]])
}
There should be 11 ui vectors to calculates "D" datas.But i have (3,11) matrix instead of 11 ui vectors.
***Here is my Ut matrix(combination of ui).Uft is transpose of Uf.
Now i want to use each row of Uft and each column of Uf and all of AT to calcutes 11 different "D".
I think you have several syntax errors to be checked:
You should use [] rather than [[]] for matrix indexing
drop = FALSE should be set
For example
for (i in 1:11) {
print(11 / 3 * Uft[, i, drop = FALSE] %*% Uf[i, , drop = FALSE] %*% AT)
}

I have to write some code but I’m completely stuck, any help would be amazing [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have to create a code or function in R that displays all the even numbers from 6:500 and beside each one any 2 prime numbers which can be added together to get said even number. I am really struggling with this and so far all I have got is a vector of the even numbers and a vector of the prime numbers. I have some idea of what I have to do but I have not clue how to code it! Any help would be greatly appreciated!
Ok, so I'm sure there's a more efficient way to do it, but you're probably going to want to nest a loop inside a loop. I'm going to use the library primes to generate my prime numbers because I'm lazy and it has a built in variable primes that contains the first 1000 primes.
library(primes)
#generate the even numbers from 6 to 500
evens <- 3:250 * 2
#generate the prime numbers less than 500
p <- primes[primes < 500]
But you said you already had that, but now I'm going to start making a data frame because I think better in data frames:
#The name of variables 'n' and 'x' are arbitrary
df <- data.frame("n" = evens,"x" = 0)
The 0 in column x is just a placeholder that I plan to fill in with my loop.
#add the library tidyverse because it contains the %in% notation that you'll want
library(tidyverse)
#start the loop and have it run from the first row to the last
for(i in 1:nrow(df)) {
#make a temp value n that will be used in the next loop
n <- df$n[i]
#start a second loop that runs through each p such that p < n
for(j in p[p < n]) {
#Take the j's and subtract them from n.
#If they are in p, then we have 2 primes that add to the right number
if((n - j) %in% p) {
#If we found one prime, them we assign it to that placeholder in x and break the loop
df$x[i] <- j
break
}
}
}
#Now that we're done, we can just add a new column that is the difference of the previous two.
df$y <- df$n - df$x

Function in R to arrange coins in staircase.Task is to determine the number of complete rows of coins in the finished staircase [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Coins arrangement Example-
If there are 6 coins then a staircase with 1 coin in the top row, 2 in the second row & 3 in the third row.So, in total 3 rows can be completed.To complete the 4th row, 4 more coins would be required i.e. in total 10 coins.
Each row should have exactly one coin more than the row above it.
I have to generate a function that arranges the coin such that, for each coins [k] function must print an integer denoting the max. no of complete rows that can be created.
Arranging coin has the following conditions-
1.coins[coins[0], -------coins[m-1] an array of long integers each representing the number of coins
2. m is in the range of 1 to 10^5.
3.coins[k] is in the range between 1 to 10^15.
The function below starts with index = 1 and keeps a running sum of the index values in sumval. It stops when sumval is greater than k and returns the index-1. This corresponds to the number of steps.
steps <- function(k) {
index <- 1
sumval <- 1
while (sumval <= k) {
index <- index + 1
sumval <- sumval + index
}
return(index-1)
}
The function took about 3.0 seconds to calculate the value for k=1e15 (44721359) on my mid-2013 MacBook Air (MacBookAir6,2).

Reduce number of elements returned by lapply [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
As ?lapply states:
lapply returns a list of the same length as X, each element of which
is the result of applying FUN to the corresponding element of X.
Is it still possible to return a list with a smaller length than X?
Code
l <- lapply(1:10,function(u)ifelse(u<5,return(u),return(NULL)))
Can I place something in the return(NULL) part in order to drop/omit the element completely?
Desired Output
Output of the code section should be the same as:
l[!sapply(l,is.null)]
a list of 4 with only elements smaller 5!
Is it still possible to return a list with a smaller length than X?
Per the documentation quoted by the OP, the answer is "no, not unless you wrap lapply in another call that filters out the unwanted elements either before or after it."
There are many possible workarounds, but I might do ...
# example function
f = function(z) c(a = list(z+1), b = list(z-1), c = if (z > 3) list(z^2))
library(data.table)
data.table(x = 1:10)[x < 5, rbindlist(lapply(x, f), fill=TRUE)]
a b c
1: 2 0 NA
2: 3 1 NA
3: 4 2 NA
4: 5 3 16
... assuming the function returns a named list. If it just returns a scalar, try vectorizing or using sapply or vapply instead of lapply.

random walk function in R [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a random walk function
random.walk = function(n){
return(cunsum(c(0, sample(c(-1, 1), size = n-1, replace =TRUE))))
}
I would like to make recursive random walk function.
what I did was
recursive.rwalk=function(n){
return(random.walk(n-1) + random.walk(n))
}
but then Im getting warning message.
Please help me out!
Thanks
You are trying to add two vectors of different lengths: n-1 and n in this line: random.walk(n-1) + random.walk(n). R is warning you that the first element of the first vector is added to the last element of the second vector (value recycling).
Altough it's obviously not a good idea to calculate a random walk recursively in R, here is how you would do that. First of all you have to recursively call the recursive.rwalk function, not the random.walk function. Next, you still need to sample each step of the way. And finally you need to tell the function when to stop recursively calling itself. Here's one way that will work:
recursive.rwalk=function(n){
if (n==0) return(0)
rw <- recursive.rwalk(n-1)
return(c(rw, rw[n-1]+sample(c(-1,1), 1)))
}
set.seed(123)
recursive.rwalk(5)
## [1] 0 1 0 1 2

Resources