Matrix solving in R with for loop [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 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)
}

Related

Finding two middle values 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 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])

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

R functions similar to "outer" but return a list [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
I have two vectors, a and b, and these two vectors are not of the same length. I wish to evaluate a function f over all possible combinations of the entries in a and b. A possible solution is:
outer(a,b,f).
However, outer function only returns 2-d array, and the function f returns a list. I am wondering whether there are functions similar to outer that can return a list.
I checked the package plyr/dplyr and didn't find a similar function. I know the problem could be solved by for-loops, nested lapply, or "outer" the arguments a and b into an array at first and then using apply. I am wondering whether there are elegant ways to solve this problem.
You could use lapply
x = 1:3
y = 6:7
1. using outer
outer(x, y, "+")
# [,1] [,2]
#[1,] 7 8
#[2,] 8 9
#[3,] 9 10
2. using lapply
lapply(x, function(a) a+y)
#[[1]]
#[1] 7 8
#[[2]]
#[1] 8 9
#[[3]]
#[1] 9 10

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

how to do looping 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 9 years ago.
Improve this question
Hey guys i want to do looping in R ; can anybody help me out
For eg i have sum of points and i want no of empid in 0-10 % of sum of points and so on ;how to do in R
For eg I have data as
empid sumofpoints
1 10
2 30
I want data as
percentageofsumpoints countofempid
0-10 4
11-20 5
21-30 6
and so on....
How to do it in R ,do i have to install any package for it
No need to install package.See http://nunn.rc.fas.harvard.edu/groups/pica/wiki/1f131/
Simple for loop
for (i in 1:10){
print(i)
}
In your example, asssuming your data is stored in a dataframe called df
res <- NULL
groups <- c(0,10,20,30,40,...)
for (i in 2:length(groups)){
res <- rbind(res,c(paste(groups[i],groups[i-1],sep="-"),nrow(df[df$sumofpoints <= groups[i] & df$sumofpoints > groups[i-1],])))
}
You can also use apply functions if you want to avoid for statements. This example I have taken directly from the help files
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
apply(x, 2, mean, trim = .2)
EDIT further to this how to avoid loops
For large dataset, refer to the package foreach. This allows for a sequential loop set-up using %do% or a parallel set-up (faster for large datasets) using %dopar%.
http://cran.r-project.org/web/packages/foreach/vignettes/foreach.pdf
For parallel computing, be mindful that you will need a backend such as "doParallel" or "DoSNOW". There is also "doMC" which only works with operating systems that support the
fork system call (which means that Windows isn't supported).

Resources