executing a command while looping through variable name fragments in R - loops

I have recently switched from STATA to R, and am stuck on some mechanisms of looping (I know looping is considered bad form here in lieu of writing a function, but my feeling is if I can figure out how to get a loop to do this, I can apply that to a function).
I regularly want to execute a call on nested variable name fragments. I cant get R to let me insert variable name fragments, either within a loop or a function; help! and while the variable name here is a number, often its a word or word fragment (a list of non-numeric, non-sequential characters, so i would like to be sure that whatever help i get isn't necessarily specific to inserting numbers!
here is an example. i would like to create an indicator variable for a patient having received a specific intervention in my dataframe called xdata. i have created several (8) intervention variables, and for each, a list of the specific patients (identified through the variable named id) who should be flagged as having received that intervention.
xdata <- data.frame(intervention1 = 0,
intervention2 = 0,
intervention3 = 0,
intervention4 = 0,
intervention5 = 0,
intervention6 = 0,
intervention7 = 0,
intervention8 = 0,
id = 1:2000)
ids <- list(dx1 = c(86, 1486, 1451),
dx2 = c(328, 1277,1458),
dx3 = c(535,1569,689),
dx4 = c(488,1335),
dx5 = c(1210,1425,932,1451,30,270,347,418,709,801,1278),
dx6 = c(282,721,749,1134),
dx7 = c(932,43,148,158,1441),
dx8 = c(932,801,1258))
for (i in 1:8) {
for (j in 1:length(ids[[i]]) {
parse(paste("xdata$intervention",i,"[xdata$id==",ids[[i]][j],"]<- 1"))
}
}
What I am hoping for the loop to do is to carry out in sequence this line of code "xdata$intervention",i,"[xdata$id==",ids[[i]][j],"]<- 1" for each iteration of a particular intervention and list of patients, as applicable. I want the loop to do this:
xdata$intervention1[xdata$id==86]<- 1
xdata$intervention1[xdata$id==1486]<- 1
xdata$intervention1[xdata$id==1451]<- 1
xdata$intervention2[xdata$id==328]<- 1
xdata$intervention2[xdata$id==1277]<- 1
xdata$intervention2[xdata$id==1458]<- 1
...
xdata$intervention8[xdata$id==932]<- 1
xdata$intervention8[xdata$id==801]<- 1
xdata$intervention8[xdata$id==1258]<- 1
Disclaimer/apology-- I have looked and looked for help with this in S.O., my guess is that the answer is out there, but one problem with being a newbie is that I have a hard time even knowing how to frame my question so the right answers will come up! If this is a duplicate I'm sorry; it was not for lack of trying that I didn't find it!

Related

Calculate change for each element in Pine Script array

I want to calculate the percent change between periods of each element in the "features" array (simply using the array as a grouping of financial time series data to report on). However the way the script is working now, it seems that it wants to calculate the percent change between each element in the array and not FOR each element in the array.
I don't think I've done anything wrong here in how I reference the array elements but I get the feeling there's some sort of 'under the hood' concept about how variables are processed by TV that is causing this issue.
//#version=4
study("My Script")
pct_change(source, period) =>
now = source
then = source[period]
missing_now = na(now)
missing_then = na(then)
if not missing_now and not missing_then
(now - then) / abs(then)
else
missing_now ? 0 : 1
evaluate(sources) =>
s = array.size(sources)
bar_changes = array.new_float()
for i = 0 to 99999
if i < s
source = array.get(sources, i)
array.push(bar_changes, pct_change(source, 1))
continue
else
break
bar_changes
features = array.new_float()
array.push(features, open)
array.push(features, high)
array.push(features, close)
bar_changes = evaluate(features)
plot(pct_change(open, 1))
plot(array.get(bar_changes, 0))
plot(pct_change(high, 1), color=color.aqua)
plot(array.get(bar_changes, 1), color=color.aqua)
plot(pct_change(close, 1), color=color.red)
plot(array.get(bar_changes, 2), color=color.red)
I think you have come across the same problem I'm faced with, and it relates to using history referencing operator [] in connection with setting array element values.
I've boiled it down to a very simple script illustrating the problem
here.
In essence what you are doing in your code is passing array element to a pct_change() function, which uses [] operator, and then use returned result in array.push() to set array element value.
I've experienced weird results when I was trying to experiment with arrays in my scripts as soon as they've been introduced, so I started to dig in order to find the root of the problem. And it came down to the script referenced in the link above. So far I believe that Pine Script still has some bugs when it comes to arrays so we just have to wait until they'll be fixed.

Removing First Value in Checkbox Table

I am making a program in Lua that has a large amount of checkboxes. Each checkbox is ID-ed from 1 to 100 in the order they appear. When a checkbox is checked, a table saves the checkbox ID and sorts it, and when it is unchecked, the table is searched for that checkbox ID and then removes it if it finds it and then sorts the table again.
However, I am having problems with the first value not removing itself. It will get removed if I check an earlier ID value and then uncheck it, but not if I try unchecking it first.
Here is the code:
switchCounter = 0
switchID = {}
--if checkbox-is-checked then
switchID[switchCounter] = checkbox.id
switchCounter = switchCounter + 1
table.sort(switchID)
--elseif checkbox-is-unchecked then
for p = 0, #switchID do
if switchID[p] == checkbox.id then
table.remove(switchID, p)
end
end
switchCounter = #switchID+1
table.sort(switchID)
The table is not altered or touched after this point (yet). It works perfectly as long as it is not the first value I am trying to remove, upon which nothing happens.
This code is utilizing the Corona SDK if that is relevant to answering.
You're confusing Lua by starting your table index at 0. In Lua, tables are 1-indexed, unlike what you're used to from most programming languages. Unfortunately, most of this code actually still works even though you're using the wrong index range. However, when you call table.remove on the first element, since your first element has index 0, you'll end up calling table.remove(switchID, 0), at which point Lua looks at you with a raised eyebrow and proceeds to do...absolutely nothing. 0 isn't a valid table index to Lua, so it doesn't remove your first element.
Change your indices to start at 1 and all should be well:
switchCounter = 1
switchID = {}
--if checkbox-is-checked then
switchID[switchCounter] = checkbox.id
switchCounter = switchCounter + 1
table.sort(switchID)
--elseif checkbox-is-unchecked then
for p = 1, #switchID do
if switchID[p] == checkbox.id then
table.remove(switchID, p)
end
end
switchCounter = #switchID+1
table.sort(switchID)
EDIT: See nobody's excellent remarks below for better information about Lua's stance on indexing.

VBA nested for loop won't Run

Hi I'm working on a macro in VBA for excel. I have a nested for loop in my code as seen below. The second loop does not run; even a MsgBox() command within the second loop doesn't result in any action and the program just seems to skip over the nested loop with no reported errors.
In plain English this nested loop should:
1) Take the string from the i entry in the array categories_string (first for loop).
2) iterate through the 300+ rows in column "AE" in the excel file (second for loop, "length" is the length of the column of data in "AE")
3) look for string matches and add 1 to the corresponding entry in the categories_value array which is populated with variables set to 0 (the if statement).
For i = LBound(categories_string) To UBound(categories_string)
For p = 1 To p = length
If Worksheets("sheet1").Cells(p + 2, "AE").Value = categories_string(i) Then
categories_value(i) = categories_value(i) + 1
End If
Next
Next
Change
For p = 1 To p = length
to
For p = 1 To length
Should fix you right up.
You may want to consider Scott Cranner's comment as well, especially if your categories_string is large and length is large. Or, just do it for the practice

Modify large cell array to find certain rows that meet a condition in MATLAB

I have a cellmatrix that I want to analyse for certain rows in MATLAB. My own solution is pretty bad (see bottom), so I thought someone could give me a hint on how to improve it. I'm pretty sure, I just have to reshape the cell array somehow, but I'm not too sure how to do that.
I have one cell with logical array entries:
TheCell{with N-rows cell}(Logical Array with varying length, but max 24 entries)
For example:
TheCell{1} = [0,1,0,1,0,0,0,0,0,1,0]
TheCell{2} = [0,0,0,0]
...
TheCell{9} = [0,1,0,0,0,0,0]
Moreover, I have one matrix called Problem that tells me at which rows in "TheCell" I'm interested in (the Problem matrix has stored some certain row indexes of TheCell):
Problem(with M-rows)
For example:
Problem = [3,5,9]
I want to find all cell entries(indexes) of TheCell, where a "1" appears in either of the following positions,:
Critical = [1;2;3;4;5;6]
So for example in row Problem(3), i.e. TheCell{9} the conditions is met at Critical(2), since:
TheCell{Problem(3)}(Critical(2)) == 1
Thus I can make a new entry in my solution matrix:
Solution(counter) = Problem(3)
Finally, I have implemented this in a bad solution, not really efficient.
Critical = [1;2;3;4;5;6];
Solution = [];
counter = 1;
for i = 1:length(Problem)
Row = Problem(i);
b = length(TheCell{Row})
for k = 1:length(Critical)
if k > b
break;
end
if TheCell{Row}(Critical(k))==1
Solution(counter) = Row;
counter = counter+1;
break;
end
end
end
Critical = 6;
find(cellfun(#(x)any(x(1:min(Critical,end))), TheCell))
or if Critical won't always be consecutive numbers starting from 1 then
Critical = [2,4,5];
find(cellfun(#(x)any(x(min(Critical,end))), TheCell))
If you have control over how TheCell is created, you can probably get a far more efficient solution by not using a cell array but rather padding the ends of each row with false.
For example
TheMatrix = false(9,24);
%// You would generate this more sensibly in your process
TheMatrix(1,1:11) = [0,1,0,1,0,0,0,0,0,1,0]
TheMatrix(2,1:4) = [0,0,0,0]
...
TheMatrix(9,1:7) = [0,1,0,0,0,0,0]
Then the solution is:
find(any(TheMatrix(:,Critical),2))

Do loop index changing on its own

I have a couple hundred line program (including functions) in essentially free-form Fortran. At one point, I have a pair of nested do loops that call functions and store results in matrices. However, I don't believe any of that is the problem (although I could be wrong).
Immediately after the first do loop starts, I define an array using a column of another array. Immediately after that, the index is always set to 3. I haven't been able to find any useful information in the usual places. I've included a fragment of the code below.
do i = 1,n
print *, 'i:',i ! Gives i = 1
applyto = eig_vec(:,i)
print *, i ! Gives i = 3
state1 = create_state(ground,applyto,state,bin_state,num_s,ns)
first = destroy_state(ground,state1,state,bin_state,num_s,ns)
state1 = destroy_state(ground,applyto,state,bin_state,num_s,ns)
second = create_state(ground,state1,state,bin_state,num_s,
1 ns)
do j = 1,n
bra = eig_vec(:,j)
a_matrix(j,i) = sum(bra*first + bra*second)
matrix(j,i) = sum(bra*first - bra*second
end do
end do
Is this a bug? Am I missing something obvious? I am compiling the code with a high level of optimization, if that could potentially be a source of problems. I'm relatively new to Fortran, so debugging flags or commands (for gdb - I believe that's all I have available) would be welcome.

Resources