Say I have the following relational schema:
+-------+------------+
| Name | Subject |
+--------------------+
| 1 | A |
| 1 | B |
| 1 | C |
| 2 | D |
| 2 | E |
| 3 | F |
| 4 | G |
| 5 | H |
| 5 | I |
+-------+------------+
and I seek these tuples:
3
4
How to get unique names for people only doing 1 subject?
Here's an example based on what AntC described:
NS={
name:string, subject:string
'1' , 'A'
'1' , 'B'
'1' , 'C'
'2' , 'D'
'2' , 'E'
'3' , 'F'
'4' , 'G'
'5' , 'H'
'5' , 'I'
}
(π name NS) - π name (σ s!=subject ((ρ s←subject NS) ⨝ NS))
If you want to test this out you can try it at:
https://dbis-uibk.github.io/relax/calc.htm
Choc Boo, welcome to stackoverflow [relational-algebra]. I strongly suggest you find yourself a textbook or online learning resource that will take you step-by-step -- preferably something you can share with other learners.
Are you sure it's RA you want to learn? Or SQL? They're very different: as a noob, learning one will probably completely confuse you wrt the other. (The connection between them won't become clear until you're much deeper in.)
There are places you can run RA online. But beware they use a specific dialect of RA, which might not be the one you're trying to learn.
Your query could perhaps be expressed as:
"Return all Names that appear in a single tuple."
Note I didn't mention "only doing 1 subject": a relation is a set; if any Name appears more than once it must be that it appears with multiple Subjects.
There's a 'quick and dirty' way to an answer: for each Name count how many tuples; restrict the result to return only those with count == 1. (That way will need using an advanced RA operator for counting.)
There's a longer-winded way that uses only more primitive operators: take two versions of your relation; pair each tuple with each from the other version; the Names that appear in more than one tuple will pair up in multiple ways same-Name-different-Subject; those are the Names you don't want.
What do I mean by "two versions"? Find out about the Rename operation (ρ). What do I mean by "pair ... with ..."? Find out about the Join operation (⋈). What do I mean by "don't want"? Find out about the set difference operator (-): I said relations are sets.
Related
I've got a query storing a UUIDv4 as a byte type in CockroachDB (v1.0). Its generated with Cockroach's documented 'uuid_v4()' function. When making selections, the results will return with the byte-typed format, like so:
"\x9d\xce`\xb3p\x9aKB\xbe\xba\xeb\xec~\x9e\xfb\x93"
while the goal is to have it output a string uuidv4, like:
"abcd-12345-asdifoekc"
I've read the casting docs on: https://www.cockroachlabs.com/docs/data-types.html#data-type-conversions--casts but still cannot figure out how to do this conversion during a SELECT statement.
Use the from_uuid() builtin, as follows:
root#:26257/> SELECT from_uuid(uuid_v4());
+--------------------------------------+
| from_uuid(uuid_v4()) |
+--------------------------------------+
| 4817bb15-4d93-4b77-b7d1-1e5cfb8360e3 |
+--------------------------------------+
(1 row)
As an illustrative example, suppose this is your dataset:
cat sex age
1 1 13
1 0 14
1 1 .
2 1 23
2 1 45
2 1 15
If you want to create a table of frequencies between cat and sex, you tabulate these two variables and you get the following result:
tab cat sex
| sex
cat | 0 1 | Total
-----------+----------------------+----------
1 | 1 2 | 3
2 | 0 3 | 3
-----------+----------------------+----------
Total | 1 5 | 6
I am writing a Stata program where the three variables are involved, i.e. cat, sex and age. Getting the matrix of frequencies for the first two variables is just an intermediate step that I need for further computation.
cap program drop myexample
program def myexample, rclass byable(recall) sortpreserve
version 14
syntax varlist [aweight iweight fweight] [if] [in] [ , AGgregate ]
args var1 var2 var3
tempname F
marksample touse
set more off
if "`aggregate'" == "" {
local var1: word 1 of `varlist'
local var2: word 2 of `varlist'
local var3: word 3 of `varlist'
qui: tab `var1' `var2' [`weight' `exp'] if `touse', matcell(`F') label matcol(`var2')
mat list `F'
}
end
However, when I run:
myexample cat sex age
I get this result which is not what I expected:
__000001[2,2]
c1 c2
r1 1 1
r2 0 3
That is, given that age contains a missing value, even if it is not directly involved in the tabulation, the program ignores the missing value and does not take into account that observation. I need to get the result of the first tabulation. I have tried using summarize instead, but the same problem arises. When implemented inside the program, missing values are not counted.
You are complaining about behaviour which you built into your own program. The responsibility and the explanation are in your hands.
The effect of
marksample touse
followed by calling up a command with the qualifier
if `touse'
is to ignore missing values. marksample by default marks as "to use" those observations in which all variables specified have non-missing values; the other observations are marked as to be ignored. It also takes account of any if or in qualifiers and any zero weights.
It's also true, as #Noobie explains, that omitting missing values from a tabulation is default for tabulate in any case.
So, to get the result you want you'd need to modify your marksample call to
marksample touse, novarlist
and to call up tabulate with the missing option (if it's compulsory) or to allow users to specify a missing option which you then pass to tabulate.
You also ask about summarize. By design that command ignores missing values. I don't know what you would expect summarize to do about them. It could report a count of missing values. If you want that, several other commands will oblige, such as codebook or missings (Stata Journal). You can always include a report on missings in your program, such as using count to count the missings and display the result.
I understand your program to be very much work in progress, so won't comment on details you don't ask about.
This is caused by marksample. Rule 5 in help mark states
The marker variable is set to 0 in observations for which any of the
numeric variables in varlist contain a numeric missing value.
You should use the novarlist option. According to the help file,
novarlist is for use with marksample. It specifies that missing values
among variables in varlist not cause the marker variable to be set to 0.
if I understand well you want tab to include missing values? If so, you just have to ask for it
tab myvar1 myvar2, mi
from the documentation
missing : treat missing values like other values
I want to auto sort values in Google Sheets as soon as I enter value in a cell. Below is an example:
| S. No. | Task | Value |
| 1 | Task 1 | $$ |
| 2 | Task 2 | $$$ |
| 3 | Task 3 | $$$$ |
| | | |
In the above table, as soon as I enter Value field for Task 3, I want it to go to top and the first one should come to the end. I don't want to achieve this manually by sorting every time.
Similar to Chris Hick's suggestion, you might enter your data in any order and have a copy sorted to suit. Since your example appears well ordered (ascending) I have assumed you would like it ordered descending (by S. No.) and that that is in A1:
=query(A:C,"Select * where A is not NULL order by A desc")
Add a couple of entries9 in A5, 8 in A6 and the resulting list will be ordered 9,8,3,2,1.
You can use a script to automatically sort your table. To do this, go to tools > script editor. This will open a new window.
Delete the code that you see and paste the below in:
function onEdit(event) {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var cellColumn = sh.getActiveRange().getColumnIndex();
var currentSheet = sh.getName();
if ((cellColumn == 3) && currentSheet == "enter sheet name here") {
var range = sh.getRange("A2:C");
range.sort({column:2, ascending:false});
}
}
You will need to change the "enter sheet name here" to the name of the sheet that you want to be sorted. Make sure to leave the quote marks in.
If you want to change the sort so that it is ascending, change the last line from
ascending:false
to
ascending:true
If you want to change the range of the data that is sorted, then you can do that on the row above. At the moment it is set to sort the range A2:C.
I want to encode a string variable in such a way that assigned numerical codes respect the original order of string values (as shown when using browse). Why? I need encoded variable labels to get the correct variable names when using reshape wide.
Suppose var is a string variable with no labels:
var label(var)
"zoo" none
"abc" none
If you start with:
encode var, gen(var2)
the labels are 1="abc" 2="zoo" as can be seen with
label li
But I want the labels sorted as they come, as shown in browse for an unchanged order of variables later.
I didn't find an encode option in which the labels are added in the order I see when using browse.
My best idea is to do it by hand:
ssc install labutil
labvalch var, f(1 2) t(2 1)
This is nice, but I have >50 list entries.
Other approach: When using reshape use another order, but I don't think that works.
reshape wide x, i(id) j(var)
I only found
ssc install labutil
labmask regioncode, values(region)
as some alternative to encode but I'm not able to cope with strings using labmask.
First off, it's a rule in Stata that string variables can't have value labels. Only numeric variables can have value labels. In essence, what you want as value labels are already in your string variable as string values. So, the nub of the problem is that you need to create a numeric variable with values in the right order.
Let's solve the problem in its easiest form: string values occur once and once only. So
gen long order = _n
labmask order, values(var)
then solves the problem, as the numeric values 1, 2, ... are linked with the string values zoo, abc, whatever, which become value labels. Incidentally, a better reference for labmask, one of mine, is
http://www.stata-journal.com/sjpdf.html?articlenum=gr0034
Now let's make it more complicated. String values might occur once or more times, but we want the numeric variable to respect first occurrence in the data.
gen long order1 = _n
egen order2 = min(order1), by(var)
egen order = group(order2)
labmask order, values(var)
Here's how that works.
gen long order1 = _n
puts the observation numbers 1, 2, whatever in a new variable.
egen order2 = min(order1), by(var)
finds the first occurrence of each distinct value of var.
egen order = group(order2)
maps those numbers to 1, 2, whatever.
labmask order, values(var)
links the numeric values of order and the string values of var, which become its value labels.
Here is an example of how that works in practice.
. l, sep(0)
+---------------------------------+
| var order1 order2 order |
|---------------------------------|
1. | zoo 1 1 zoo |
2. | abc 2 2 abc |
3. | zoo 3 1 zoo |
4. | abc 4 2 abc |
5. | new 5 5 new |
6. | newer 6 6 newer |
+---------------------------------+
. l, nola sep(0)
+---------------------------------+
| var order1 order2 order |
|---------------------------------|
1. | zoo 1 1 1 |
2. | abc 2 2 2 |
3. | zoo 3 1 1 |
4. | abc 4 2 2 |
5. | new 5 5 3 |
6. | newer 6 6 4 |
+---------------------------------+
You would drop order1 order2 once you have got the right answer.
See also sencode for another solution. (search sencode to find references and download locations.)
The user-written command sencode (super encode) by Roger Newson, and available running ssc describe sencode can be used for what you want. Instead of assigning numerical codes based on the alphanumeric order of the string variable, they can be assigned using the order in which the values appear in the original dataset.
clear all
set more off
*------- example data ---------
input str10 var
abc
zoo
zoo
zoo
elephant
elephant
abc
abc
elephant
zoo
end
*------- encode ---------------
encode var, generate(var2)
sencode var, generate(var3)
list, separator(0)
list, separator(0) nolabel
The variable var3 is in the desired form. Contrast that with var2.
I'm not sure if there's an elegant solution, because I think that levelsof orders strings alphabetically.
As long as your list is unique this should work.
clear
input str3 myVar
"zoo"
"abc"
"def"
end
* for reshape
generate iVar = 1
generate jVar = _n
* reshape to wide
reshape wide myVar, i(iVar) j(jVar)
list
* create label
local i = 0
foreach v of varlist myVar* {
local ++i
local myVarName = `v'
label define myLabel `i' "`myVarName'", add
}
* reshape to wide
reshape long myVar, i(iVar) j(myVarEncoded)
* assign label
label value myVarEncoded myLabel
Ruby noob here!
I have an array of structs that look like this
Token = Struct.new(:token, :ordinal)
So an array of these would look like this, in tabular form:
Token | Ordinal
---------------
C | 2
CC | 3
C | 5
And I want to group by the "token" (i.e. the left hand column) of the struct and get a count, but also preserve the "ordinal" element. So the above would look like this
Token | Merged Ordinal | Count
------------------------------
C | 2, 5 | 2
CC | 3 | 1
Notice that the last column is a count of the grouped tokens and the middle column merges the "ordinal". The first column ("Token") can contain a variable number of characters, and I want to group on these.
I have tried various methods, using group_by (I can get the count, but not the middle column), inject, iterating (does not seem very functional) but I just can't get it right, partly because I don't have a good grasp of Ruby and the available operations / functions.
I have also had a good look around SO, but I am not getting very far.
Any help, pointers would be much appreciated!
Use Enumerable#group_by to do the grouping for you and use the resulting hash to get what you want with map or similar.
structs.group_by(&:token).map do |token, with_same_token|
[token, with_same_token.map(&:ordinal), with_same_token.size]
end