how to do looping 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 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).

Related

How to save a calculation to a variable using variables that have not been defined yet? [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 last month.
Improve this question
Let's say I have a script, where I have a calculation like this:
calculation = c(
a*b +
c*d +
e*f
)
And then in another script I want to call that calculation using the source command.
I get an error saying "Object 'a' not found". What am I doing wrong?
Edit: I don't want to make a function, because this specific calculation is used as input in a complex program in r (apollo) - the input specifies a utility function in a logit regression.
You can capture your expression using expression(), then when you're ready, evaluate using eval():
calculation <- expression(a*b + d*e + f*g)
a <- 1
b <- 2
d <- 3
e <- 4
f <- 5
g <- 6
eval(calculation)
# 44

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

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

Use R to translate 'coded' table [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem with using R to 'translate' back a coded table. So I have a table with table elements consisting of XX,XY,YY. I have a second table (.csv) with the proper meaning of the X and Y - so it might look like, if X=1 and Y=2,
XY is transformed into 12
XX is transformed into 11 ...
can anybody hint at a good starting point to write such a program/ piece of code in R?
This is slightly different than a lookup table in that you're actually regexing and replacing parts of each element. The qdap (Quantitative Discourse Analysis Package) has a mgsub (multiple gsub) function that can handle this easily.
library(qdap)
#recreate scenerio with quick character vector (no need for quotes)
z <- factor(qcv(XX,XY,YY))
#replace all X and Ys with 1 and 2
mgsub(pattern = c("X", "Y"), replacement = c(1, 2), text.var = z)
#Even better if you have the code book read in, say it looks like this:
code.book <- data.frame(symb = c("X", "Y"), replacement = c(1, 2))
# > code.book
# symb replacement
# 1 X 1
# 2 Y 2
mgsub(code.book$symb, code.book$replacement, z)

Resources