cross
Pairs every row here with every row in the other file.
What we have
- every row here paired with every row there
Coming later
Nothing known to be missing.
How you write it
cross using "file.dta"
Square brackets mean optional. A vertical bar means choose one.
What it does
A join with no key at all — every combination of the two. Its real use is building a complete frame to check against: all states crossed with all years gives you the grid your data ought to fill, and merging your data onto it shows exactly which state-years are missing.
Watch out. The two files must not share any column names, and the result is the two row counts multiplied together.
Try it
Every example below was run after sysuse vira.sample03, clear.
. keep dept
The same thing in pandas and in R
pandas
df = df[['dept']]
R
library(dplyr) df <- df %>% select(dept) # This R was run in a real R (4.6.1) and gave the same numbers.
. keep in 1/3
(3,997 observations deleted)
The same thing in pandas and in R
pandas
import numpy as np mask = (np.arange(1, len(df) + 1) >= 1) & (np.arange(1, len(df) + 1) <= 3) df = df[mask].reset_index(drop=True)
R
library(dplyr) df <- df %>% filter(row_number() >= 1 & row_number() <= 3) # This R was run in a real R (4.6.1) and gave the same numbers.
. save "small.dta", replace
file small.dta saved
The same thing in pandas and in R
pandas
df.to_stata("small.dta", write_index=False)
R
library(haven) write_dta(df, "small.dta") # This R has NOT been run against a real R yet: read it as documentation.
. sysuse vira.sample02, clear
(6,000 observations read from vira.sample02.dta)
The same thing in pandas and in R
R
library(haven)
df <- read_dta("vira.sample02.dta")
# This R has NOT been run against a real R yet: read it as documentation.
. keep state
The same thing in pandas and in R
pandas
df = df[['state']]
R
library(dplyr) df <- df %>% select(state) # This R was run in a real R (4.6.1) and gave the same numbers.
. keep in 1/2
(5,998 observations deleted)
The same thing in pandas and in R
pandas
import numpy as np mask = (np.arange(1, len(df) + 1) >= 1) & (np.arange(1, len(df) + 1) <= 2) df = df[mask].reset_index(drop=True)
R
library(dplyr) df <- df %>% filter(row_number() >= 1 & row_number() <= 2) # This R was run in a real R (4.6.1) and gave the same numbers.
. cross using "small.dta"
(2 x 3 = 6 observations)
The same thing in pandas and in R
pandas
import pandas as pd
other = pd.read_stata('small.dta')
df = df.merge(other, how='cross')
R
# no R form for `cross` yet -- see docs/r-equivalents.md