R: annotate within an equation - r

Is it possible to annotate within an equation in R? For example:
100 /* item 1 */ + 200 /* item 2 */
giving an answer of 300.
I think /* */ is C code. Although, I am not certain 100 /* item 1 */ + 200 /* item 2 */ will run in C.
If I use 100 # item 1 # + 200 # item 2 # in R I get an answer of 100 because everything after the first # is ignored, as I expected.
I suppose I could use:
# item 1 item 2
100 + 200
I was just thinking that when equations become really long and complex taking up several lines it might be nice to annotate within an equation.
The following works and returns 300:
(100 + # item 1
200 ) # item 2
That requires a new line after every annotation and is the closest that I can come to my initial example above containing only one line.
Thanks for any advice.

It's not possible. As noted in the Comments section of the R language manual, the only comment character is #. Everything from the # to the end of the line is ignored (unless the # is quoted in a string).

Related

Specify range from -x to x

I want my code to count up to a number n and then down to where it started, for example of n=4:
1
2
3
4
3
2
1
I've used range() to get from 1-4, and then reversed(range()) to get to 4-1, but they're two seperate blocks (and I'd get two 4's) and I'm sure there is a better and cleaner way. I've tried to specify the range from -n to n, but I honestly have no idea if I should use length, range or slices or whatever. I'm very new to programming.
You are missing the abs function as well to figure this out.
Try something like the following
n = 4;
for i in map(lambda x: n - abs(x),range(0-n+1, n)):
print(i)
Output should be like the following,
1
2
3
4
3
2
1
You could also wrap this and return an enumerator like the following,
def riseAndFall(n):
for i in map(lambda x: n - abs(x),range(0-n+1, n)):
yield i
for i in riseAndFall(4):
print(i)

i not showing up as number in loop

so I have a loop that finds the position in the matrix where there is the largest difference in consecutive elements. For example, if thematrix[8] and thematrix[9] have the largest difference between any two consecutive elements, the number given should be 8.
I made the loop in a way that it will ignore comparisons where one of the elements is NaN (because I have some of those in my data). The loop I made looks like this.
thenumber = 0 #will store the difference
for (i in 1:nrow(thematrix) - 1) {
if (!is.na(thematrix[i]) & !is.na(thematrix[i + 1])) {
if (abs(thematrix[i] - thematrix[i + 1]) > thenumber) {
thenumber = i
}
}
}
This looks like it should work but whenever I run it
Error in if (!is.na(thematrix[i]) & !is.na(thematrix[i + 1])) { :
argument is of length zero
I tried this thing but with a random number in the brackets instead of i and it works. For some reason it only doesn't work when I use the i specified in the beginning of the for-loop. It doesn't recognize that i represents a number. Why doesn't R recognize i?
Also, if there's a better way to do this task I'd appreciate it greatly if you could explain it to me
You are pretty close but when you call i in 1:nrow(thematrix) - 1 R evaluates this to make i = 0 which is what causes this issue. I would suggest either calling i in 1:nrow(thematrix) or i in 2:nrow(thematrix) - 1 to start your loop at i = 1. I think your approach is generally pretty intuitive but one suggestion would be to frequently use the print() function to evaluate how i changes over the course of your function.
The issue is that the : operator has higher precedence than -; you just need to use parentheses around (nrow(thematrix)-1). For example,
thematrix <- matrix(1:10, nrow = 5)
##
wrong <- 1:nrow(thematrix) - 1
right <- 1:(nrow(thematrix) - 1)
##
R> wrong
#[1] 0 1 2 3 4
R> right
#[1] 1 2 3 4
Where the error message is coming from trying to access the zero-th element of thematrix:
R> thematrix[0]
integer(0)
The other two answers address your question directly, but I must say this is about the worst possible way to solve this problem in R.
set.seed(1) # for reproducible example
x <- sample(1:10,10) # numbers 1:10 in random order
x
# [1] 3 4 5 7 2 8 9 6 10 1
which.max(abs(diff(x)))
# [1] 9
The diff(...) function calculates sequential differences, and which.max(...) identifies the element number of the maximum value in a vector.

Barplot in R - How to divide the plot into separate parts by showing them in different colors

I am a newbie to R. I would like to create a barplot which is visually divided into different parts.
My data looks like the following:
"1.0";"0.0";"1.0";"2.0";"710";"12500"
first four numbers give the number of parts that need to be ordered from the two parts list below. The fifth number gives the result sum of the first part, the sixth then the result sum of the second part.
part 1: 10;50;100;300
part 2: 500;1000;2000;5000;
this is how it is calculated.
1 * 10 + 0 * 50 + 1 * 100 + 2 * 300 = 710 ;
1 * 500 + 0 * 1000 + 1 * 2000 + 2 * 5000 = 12500
So what I now want to plot is for example the value 12500, but I want to visually divide this value into the different part (stacked bars) like two five thousands, then one two thousand then one five hundred -> the bar should consist of these parts which can visually be seen or marked with the value (would be nice to have different colors for each part in the part)
How can I do it? Folks, I did my homework, I searched a lot and did try it on my own, but couldn't achieve what I want.
daten <- matrix(c(10,50,100,300,500,1000,2000,5000),ncol=2)
multiplier <- c(1,0,1,2)
barplot(daten*multiplier)
To display bar segments in reverse order, you need to rearrange the rows in the daten*multiplier array:
barplot((daten*multiplier)[nrow(daten):1,])

How can I modify this (simple) equation to produce my desired result?

I have a database of 817 items, each given a "rank" of 1 to 817 (the smaller the number, the "better" the item). This rank is based off of many factors that indicate quality.
Now, I need to assign a "value" to these items, with the item at rank 1 being valued the most, and the value decreasing with rank (non-linear).
The easiest first attempt was to simply choose an arbitrary base (100,000) and divide by the rank:
$value = 100000 / $rank;
/**
* Rank : Value
* 1 : 100,000
* 2 : 50,000
* 3 : 33,333
* etc.
*/
This produces exponential decay, as shown in the red line in this image:
However, I wish to value these items in a manner that looks more like the blue line above. How can I change my formula to achieve this?
Try 1/sqrt(x) (i.e, pow(x, -1/2)) for starters. If that's still not slow enough, try a smaller fractional power.
Why don't you go with linear?
value = n - rank
where n is the count of your items, i.e. 817.
I haven't tried but use exponent instead of dividing by 1000 of a base 2.
UPDATES
value = 2 pow (n-rank)

How do I calculate the number of permutations in base 3 combinatorics?

I've never been much for math and I'm hoping that someone can help me out with the following.
I have 5 boxes:
1 2 3 4 5
[ ] [ ] [ ] [ ] [ ]
The boxes can either be white, gray, or black (or think of it as 0, 1, 2)
How many possible states can the box set be in?
What is the pseudocode (or in any language) to generate all the possible outcomes??
ie...
00000
00001
00011
00111
etc, etc...
I really appreciate any help anyone can give me with this.
the answer for the number of combinations is: 3x3x3x3x3 (3^5) since each box can have 3 possible colors.
As for generating the outcomes, see if you can figure it out using this matrix with 0, 1, or 2 to represent the color of the box. On a smaller scale (lets assume 3 boxes) it would look like this:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
2 2 0
2 2 1
2 2 2
This is a classic permutation generation problem. You have 3 possibilities for each position, and 5 positions. The total number of generated string is 3^5 = 243.
You need recursion if you want a general solution (a simple iterative loop only works for a single instance of the problem).
Here's a quick example:
public static void Main(string[] args){
Generate("", 5);
}
private void Generate(string s, int limit)
{
if (s.Length == limit)
Console.WriteLine(s);
else
{
Generate(s+"0", limit);
Generate(s+"1", limit);
Generate(s+"2", limit);
}
}
To answer your first question, what would the answer be if the boxes could contain only one of two values? So, what's the answer if the boxes contain one of three values?
To answer your second question, what pseudocode generates all possible outcomes of one box? Now, pseudocode generates all possible outcomes of two boxes?
I'd recommend solving the problem on paper first. Try to solve it with a smaller number of boxes (maybe three), and list all possibilities. Then, think of how your reasoning went, or how you'd explain what you did to a small child.
This seems like a homework problem. I'll just give you some help as to the solution then.
What you are saying is that each box has three states, which are all independent. One box would have 3 solutions, and two boxes would have 3 * 3 solutions - for each state of the first box the second box would have three states as well. Extend that to 5 boxes.
To generate each solution, you can just cycle through it. It is easy to make nested for loops for each box, and multiplying by powers of 10 can let you show the number at once.
You can generalize the code for multiple boxes in a similar way.
Thank you all for your answers, at least those of you who actually gave me one.
While I can appreciate that the question sounded like it was pulled straight out of Computer Science 101, it wasn't. The irony of the matter is that it was for real life on a real deadline and I didn't have time to hearken back to when I was being taught this stuff and said to myself, "when am I ever going to need this crap"
If I wanted to be patronized and treated like a school boy I would go back to my elementary school and ask my 5th grade teacher if I can go to the bathroom
Thanks again
the number of states is 3^5.
pseudocode is
for value from 0 to 3^5-1
print base3(value)
where base3 is a function that repeatedly takes modulo 3 to get a digit, then removes that digit (by dividing by 3)
Hint: imagine that each box is a position in a number and each colour is a different digit. In the real world, how many combinations (including zero) do you get with 2 positions and 10 possible digits? What about 3 positions? What's the relationship between adding an extra position and the number of combinations, given the number of digits you have available?
Unique number of combinations: 3^5=243
Code:
n = 0
for i = 0 to 3^5-1
{
s = ""
for j = 1 to 5
{
d = n mod 3
s = toascii(d) . s
n = n / 3
}
println s
i = i + 1
}
Here's how I first learned to do this: first think about how many choices you are making. You are making five choices, one for each box. So write down five blank lines with multiplication signs:
__ x __ x __ x __ x __ = ?
In each blank, write the number of objects you have to choose from for that box. Since you have 3 numbers to choose from for each box, you write a 3 in every blank:
3 x 3 x 3 x 3 x 3 = 243
This gives you the total number of permutations for those choices.
The number of possibilities is 3 to the power 5
If you loop from 0 to that number minus 1 and express it in base 3 you will have all the possibilities (remember to prepend 0s where necessary)
In Ruby:
number_of_possibilities = 3**5-1
for i in (0..number_of_possibilities)
base_3_number = i.to_s(3)
puts "%05d" % base_3_number # number formatting used to prepend 0s where necessary
end
Can I ask what about this you don't understand or whats tripping you up? I see that everyone here has simply answered the question, but if you've copied their answers, you've learned nothing, and thus completely missed the point of the homework. Assuming your next lesson builds upon this one, you're just going to fall further behind.
If you either worked for me or were in my class I'd simply ask the following...
"How do you think the problem should be solved?" The answer to which might reveal where you're getting hung up. A wise professor of mine at CMU once said "I can't help you understand this until you know what you don't understand" I never did figure out what I didn't understand and I dropped his class, but the lesson stuck with me.
I know its probably too late, but for these homework questions I really think we should be helping the person learn as opposed to simply providing an answer and doing their homework for them.
Your problem needs nothing more than the rule of product in combinatorics.
You can choose the state of the first box in 3 ways, and the state of the second box in 3 ways, and ... and the state of the 5th box in 3 ways. The number of ways in which you can set the state of all the boxes is the product of all the five (equal) numbers of ways, i.e. 3x3x3x3x3 = 35.
Similar question: how many numbers can you form with 5 digits in the decimal system, counting the leading zeros? That is, how many numbers are there from 00000 to 99999? You can choose the first digit in 10 ways (0...9), and so on and so on, and the answer is 10x10x10x10x10 = 100000, as you already know.
Don't even try to write code to answer this! The reason is that you need some very large numbers (factorials) to calculate it. These create numbers much larger than any base type in the CLR. You can use this opensource library to do the calculation.
void solve(int p=0,int n=5,int d=0)
{
if (n==p)
{
int rev=d;
int i=0;
while (i<5) {
cout << rev%10;
rev /= 10;
i++;## Heading ##
}
cout << endl;
return;
}
for(int i=0; i<3 ; i++)
{
solve(p+1,n, d*10 + i);
}
}

Resources