Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

# -*- coding: utf-8 -*- 

r""" 

Interfaces to R 

 

This is the reference to the Sagemath R interface, usable from any 

Sage program. 

 

The %r interface creating an R cell in the sage 

notebook is decribed in the Notebook manual. 

 

The %R and %%R interface creating an R line or an R cell in the 

Jupyter notebook are briefly decribed at the end of this page. This 

documentation will be expanded and placed in the Jupyter notebook 

manual when this manual exists.  

 

The following examples try to follow "An Introduction to R" which can 

be found at http://cran.r-project.org/doc/manuals/R-intro.html . 

 

EXAMPLES: 

 

Simple manipulations; numbers and vectors 

 

The simplest data structure in R is the numeric vector which 

consists of an ordered collection of numbers. To create a 

vector named $x$ using the R interface in Sage, you pass the 

R interpreter object a list or tuple of numbers:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]); x 

[1] 10.4 5.6 3.1 6.4 21.7 

 

You can invert elements of a vector x in R by using the 

invert operator or by doing 1/x:: 

 

sage: ~x 

[1] 0.09615385 0.17857143 0.32258065 0.15625000 0.04608295 

sage: 1/x 

[1] 0.09615385 0.17857143 0.32258065 0.15625000 0.04608295 

 

The following assignment creates a vector $y$ with 11 entries which 

consists of two copies of $x$ with a 0 in between:: 

 

sage: y = r([x,0,x]); y 

[1] 10.4 5.6 3.1 6.4 21.7 0.0 10.4 5.6 3.1 6.4 21.7 

 

Vector Arithmetic 

 

The following command generates a new vector $v$ of length 11 constructed 

by adding together (element by element) $2x$ repeated 2.2 times, $y$ 

repeated just once, and 1 repeated 11 times:: 

 

sage: v = 2*x+y+1; v 

[1] 32.2 17.8 10.3 20.2 66.1 21.8 22.6 12.8 16.9 50.8 43.5 

 

One can compute the sum of the elements of an R vector in the following 

two ways:: 

 

sage: sum(x) 

[1] 47.2 

sage: x.sum() 

[1] 47.2 

 

One can calculate the sample variance of a list of numbers:: 

 

sage: ((x-x.mean())^2/(x.length()-1)).sum() 

[1] 53.853 

sage: x.var() 

[1] 53.853 

 

sage: x.sort() 

[1] 3.1 5.6 6.4 10.4 21.7 

sage: x.min() 

[1] 3.1 

sage: x.max() 

[1] 21.7 

sage: x 

[1] 10.4 5.6 3.1 6.4 21.7 

 

sage: r(-17).sqrt() 

[1] NaN 

sage: r('-17+0i').sqrt() 

[1] 0+4.123106i 

 

Generating an arithmetic sequence:: 

 

sage: r('1:10') 

[1] 1 2 3 4 5 6 7 8 9 10 

 

Because ``from`` is a keyword in Python, it can't be used 

as a keyword argument. Instead, ``from_`` can be passed, and 

R will recognize it as the correct thing:: 

 

sage: r.seq(length=10, from_=-1, by=.2) 

[1] -1.0 -0.8 -0.6 -0.4 -0.2 0.0 0.2 0.4 0.6 0.8 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]); 

sage: x.rep(2) 

[1] 10.4 5.6 3.1 6.4 21.7 10.4 5.6 3.1 6.4 21.7 

sage: x.rep(times=2) 

[1] 10.4 5.6 3.1 6.4 21.7 10.4 5.6 3.1 6.4 21.7 

sage: x.rep(each=2) 

[1] 10.4 10.4 5.6 5.6 3.1 3.1 6.4 6.4 21.7 21.7 

 

Missing Values:: 

 

sage: na = r('NA') 

sage: z = r([1,2,3,na]) 

sage: z 

[1] 1 2 3 NA 

sage: ind = r.is_na(z) 

sage: ind 

[1] FALSE FALSE FALSE TRUE 

sage: zero = r(0) 

sage: zero / zero 

[1] NaN 

sage: inf = r('Inf') 

sage: inf-inf 

[1] NaN 

sage: r.is_na(inf) 

[1] FALSE 

sage: r.is_na(inf-inf) 

[1] TRUE 

sage: r.is_na(zero/zero) 

[1] TRUE 

sage: r.is_na(na) 

[1] TRUE 

sage: r.is_nan(inf-inf) 

[1] TRUE 

sage: r.is_nan(zero/zero) 

[1] TRUE 

sage: r.is_nan(na) 

[1] FALSE 

 

 

Character Vectors:: 

 

sage: labs = r.paste('c("X","Y")', '1:10', sep='""'); labs 

[1] "X1" "Y2" "X3" "Y4" "X5" "Y6" "X7" "Y8" "X9" "Y10" 

 

 

Index vectors; selecting and modifying subsets of a data set:: 

 

sage: na = r('NA') 

sage: x = r([10.4,5.6,3.1,6.4,21.7,na]); x 

[1] 10.4 5.6 3.1 6.4 21.7 NA 

sage: x['!is.na(self)'] 

[1] 10.4 5.6 3.1 6.4 21.7 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7,na]); x 

[1] 10.4 5.6 3.1 6.4 21.7 NA 

sage: (x+1)['(!is.na(self)) & self>0'] 

[1] 11.4 6.6 4.1 7.4 22.7 

sage: x = r([10.4,-2,3.1,-0.5,21.7,na]); x 

[1] 10.4 -2.0 3.1 -0.5 21.7 NA 

sage: (x+1)['(!is.na(self)) & self>0'] 

[1] 11.4 4.1 0.5 22.7 

 

Distributions:: 

 

sage: r.options(width="60"); 

$width 

[1] 100 

 

sage: rr = r.dnorm(r.seq(-3,3,0.1)) 

sage: rr 

[1] 0.004431848 0.005952532 0.007915452 0.010420935 

[5] 0.013582969 0.017528300 0.022394530 0.028327038 

[9] 0.035474593 0.043983596 0.053990967 0.065615815 

[13] 0.078950158 0.094049077 0.110920835 0.129517596 

[17] 0.149727466 0.171368592 0.194186055 0.217852177 

[21] 0.241970725 0.266085250 0.289691553 0.312253933 

[25] 0.333224603 0.352065327 0.368270140 0.381387815 

[29] 0.391042694 0.396952547 0.398942280 0.396952547 

[33] 0.391042694 0.381387815 0.368270140 0.352065327 

[37] 0.333224603 0.312253933 0.289691553 0.266085250 

[41] 0.241970725 0.217852177 0.194186055 0.171368592 

[45] 0.149727466 0.129517596 0.110920835 0.094049077 

[49] 0.078950158 0.065615815 0.053990967 0.043983596 

[53] 0.035474593 0.028327038 0.022394530 0.017528300 

[57] 0.013582969 0.010420935 0.007915452 0.005952532 

[61] 0.004431848 

 

Convert R Data Structures to Python/Sage:: 

 

sage: rr = r.dnorm(r.seq(-3,3,0.1)) 

sage: sum(rr._sage_()) 

9.9772125168981... 

 

Or you get a dictionary to be able to access all the information:: 

 

sage: rs = r.summary(r.c(1,4,3,4,3,2,5,1)) 

sage: rs 

Min. 1st Qu. Median Mean 3rd Qu. Max. 

1.000 1.750 3.000 2.875 4.000 5.000 

sage: d = rs._sage_() 

sage: d['DATA'] 

[1, 1.75, 3, 2.875, 4, 5] 

sage: d['_Names'] 

['Min.', '1st Qu.', 'Median', 'Mean', '3rd Qu.', 'Max.'] 

sage: d['_r_class'] 

['summaryDefault', 'table'] 

 

It is also possible to access the plotting capabilities of R 

through Sage. For more information see the documentation of 

r.plot() or r.png(). 

 

THE JUPYTER NOTEBOOK INTERFACE (work in progress). 

 

The %r interface described in the Sage notebook manual is not useful 

in the Jupyter notebook : it creates a inferior R interpreter which 

cannot be escaped. 

 

The RPy2 library allows the creation of an R cell in the Jupyter 

notebook analogous to the %r escape in command line or %r cell in a 

Sage notebook. 

 

The interface is loaded by a cell containing the sole code : 

 

"%load_ext rpy2.ipython" 

 

After execution of this code, the %R and %%R magics are available : 

 

- %R allows the execution of a single line of R code. Data exchange is 

possible via the -i and -o options. Do "%R?" in a standalone cell 

to get the documentation. 

 

- %%R allows the execution in R of the whole text of a cell, with 

similar options (do "%%R?" in a standalone cell for 

documentation). 

 

A few important points must be noted : 

 

- The R interpreter launched by this interface IS (currently) 

DIFFERENT from the R interpreter used br other r... functions. 

 

- Data exchanged via the -i and -o options have a format DIFFERENT 

from the format used by the r... functions (RPy2 mostly uses arrays, 

and bugs the user to use the pandas Python package). 

 

- R graphics are (beautifully) displayed in output cells, but are not 

directly importable. You have to save them as .png, .pdf or .svg 

files and import them in Sage for further use.  

 

In its current incarnation, this interface is mostly useful to 

statisticians needing Sage for a few symbolic computations but mostly 

using R for applied work. 

 

AUTHORS: 

 

- Mike Hansen (2007-11-01) 

- William Stein (2008-04-19) 

- Harald Schilly (2008-03-20) 

- Mike Hansen (2008-04-19) 

- Emmanuel Charpentier (2015-12-12, RPy2 interface) 

""" 

 

########################################################################## 

# 

# Copyright (C) 2007 William Stein <wstein@gmail.com> 

# 2007 Mike Hansen <mhansen@gmail.com> 

# 2008 Harald Schilly <harald.schilly@gmail.com> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# 

# http://www.gnu.org/licenses/ 

# 

########################################################################## 

from __future__ import print_function, absolute_import 

from six.moves import range 

import six 

 

from .expect import Expect, ExpectElement, ExpectFunction, FunctionElement 

from sage.env import DOT_SAGE 

import re 

import sage.rings.integer 

from sage.structure.element import parent 

from sage.misc.cachefunc import cached_method 

from sage.interfaces.tab_completion import ExtraTabCompletion 

from sage.docs.instancedoc import instancedoc 

 

COMMANDS_CACHE = '%s/r_commandlist.sobj'%DOT_SAGE 

PROMPT = '__SAGE__R__PROMPT__> ' 

prompt_re = re.compile("^>", re.M) 

 

#there is a mirror network, but lets take #1 for now 

RRepositoryURL = "http://cran.r-project.org/" 

RFilteredPackages = ['.GlobalEnv'] 

 

# crosscheck with https://svn.r-project.org/R/trunk/src/main/names.c 

# but package:base should cover this. i think. 

RBaseCommands = ['c', "NULL", "NA", "True", "False", "Inf", "NaN"] 

 

class R(ExtraTabCompletion, Expect): 

def __init__(self, 

maxread=None, script_subdirectory=None, 

server_tmpdir = None, 

logfile=None, 

server=None, 

init_list_length=1024, 

seed=None): 

""" 

An interface to the R interpreter. 

 

R is a comprehensive collection of methods for statistics, 

modelling, bioinformatics, data analysis and much more. 

For more details, see http://www.r-project.org/about.html 

 

Resources: 

 

* http://r-project.org/ provides more information about R. 

* http://rseek.org/ R's own search engine. 

 

EXAMPLES:: 

 

sage: r.summary(r.c(1,2,3,111,2,3,2,3,2,5,4)) 

Min. 1st Qu. Median Mean 3rd Qu. Max. 

1.00 2.00 3.00 12.55 3.50 111.00 

 

TESTS:: 

 

sage: r == loads(dumps(r)) 

True 

""" 

Expect.__init__(self, 

 

# The capitalized version of this is used for printing. 

name = 'r', 

 

# This is regexp of the input prompt. If you can change 

# it to be very obfuscated that would be better. Even 

# better is to use sequence numbers. 

# options(prompt=\"<prompt> \") 

prompt = '> ', #default, later comes the change 

 

# This is the command that starts up your program 

command = "R --vanilla --quiet", 

 

server=server, 

server_tmpdir=server_tmpdir, 

 

script_subdirectory = script_subdirectory, 

 

# If this is true, then whenever the user presses Control-C to 

# interrupt a calculation, the whole interface is restarted. 

restart_on_ctrlc = False, 

 

# If true, print out a message when starting 

# up the command when you first send a command 

# to this interface. 

verbose_start = False, 

 

logfile=logfile, 

 

# If an input is longer than this number of characters, then 

# try to switch to outputting to a file. 

eval_using_file_cutoff=1024) 

 

self.__seq = 0 

self.__var_store_len = 0 

self.__init_list_length = init_list_length 

self._prompt_wait = [self._prompt] 

self._seed = seed 

 

def set_seed(self, seed=None): 

""" 

Set the seed for R interpreter. 

 

The seed should be an integer. 

 

EXAMPLES:: 

 

sage: r = R() 

sage: r.set_seed(1) 

1 

sage: r.sample("1:10", 5) 

[1] 3 4 5 7 2 

""" 

if seed is None: 

seed = self.rand_seed() 

self.eval('set.seed(%d)' % seed) 

self._seed = seed 

return seed 

 

def _start(self): 

""" 

Start up the R interpreter and sets the initial prompt and options. 

 

This is called the first time the R interface is actually used. 

 

EXAMPLES:: 

 

sage: r = R() 

sage: r._start() 

""" 

Expect._start(self) 

 

# width is line width, what's a good value? maximum is 10000! 

# pager needed to replace help view from less to printout 

# option device= is for plotting, is set to x11, NULL would be better? 

self._change_prompt(PROMPT) 

self.eval('options(prompt=\"%s\",continue=\"%s\", width=100,pager="cat",device="png")'%(PROMPT, PROMPT)) 

self.expect().expect(PROMPT) 

self.eval('options(repos="%s")'%RRepositoryURL) 

self.eval('options(CRAN="%s")'%RRepositoryURL) 

 

# don't abort on errors, just raise them! 

# necessary for non-interactive execution 

self.eval('options(error = expression(NULL))') 

 

# set random seed 

self.set_seed(self._seed) 

 

def png(self, *args, **kwds): 

""" 

Creates an R PNG device. 

 

This should primarily be used to save an R graphic to a custom file. Note 

that when using this in the notebook, one must plot in the same cell that 

one creates the device. See r.plot() documentation for more information 

about plotting via R in Sage. 

 

These examples won't work on the many platforms where R still gets 

built without graphics support. 

 

EXAMPLES:: 

 

sage: filename = tmp_filename() + '.png' 

sage: r.png(filename='"%s"'%filename) # optional -- rgraphics 

NULL 

sage: x = r([1,2,3]) 

sage: y = r([4,5,6]) 

sage: r.plot(x,y) # This saves to filename, but is not viewable from command line; optional -- rgraphics 

null device 

1 

sage: import os; os.unlink(filename) # We remove the file for doctesting; optional -- rgraphics 

 

We want to make sure that we actually can view R graphics, which happens 

differently on different platforms:: 

 

sage: s = r.eval('capabilities("png")') # Should be on Linux and Solaris 

sage: t = r.eval('capabilities("aqua")') # Should be on all supported Mac versions 

sage: "TRUE" in s+t # optional -- rgraphics 

True 

""" 

#Check to see if R has PNG support 

s = self.eval('capabilities("png")') 

t = r.eval('capabilities("aqua")') 

if "TRUE" not in s+t: 

raise RuntimeError("R was not compiled with PNG support") 

 

from sage.server.support import EMBEDDED_MODE 

if EMBEDDED_MODE: 

self.setwd('"%s"'%os.path.abspath('.')) 

return RFunction(self, 'png')(*args, **kwds) 

 

def convert_r_list(self, l): 

r""" 

Converts an R list to a Python list. 

 

EXAMPLES:: 

 

sage: s = 'c(".GlobalEnv", "package:stats", "package:graphics", "package:grDevices", \n"package:utils", "package:datasets", "package:methods", "Autoloads", \n"package:base")' 

sage: r.convert_r_list(s) 

['.GlobalEnv', 

'package:stats', 

'package:graphics', 

'package:grDevices', 

'package:utils', 

'package:datasets', 

'package:methods', 

'Autoloads', 

'package:base'] 

""" 

pl = [] 

l = "".join(l.split("\n")) 

l = l[2:len(l)-1] 

for l in l.split(","): 

pl.append(l.strip().strip('"')) 

return pl 

 

def install_packages(self, package_name): 

""" 

Install an R package into Sage's R installation. 

 

EXAMPLES:: 

 

sage: r.install_packages('aaMI') # not tested 

... 

R is free software and comes with ABSOLUTELY NO WARRANTY. 

You are welcome to redistribute it under certain conditions. 

Type 'license()' or 'licence()' for distribution details. 

... 

Please restart Sage in order to use 'aaMI'. 

""" 

cmd = """options(repos="%s"); install.packages("%s")"""%(RRepositoryURL, package_name) 

os.system("time echo '%s' | R --vanilla"%cmd) 

print("Please restart Sage in order to use '%s'." % package_name) 

 

def _repr_(self): 

""" 

Return string representation of this R interface. 

 

EXAMPLES:: 

 

sage: r # indirect doctest 

R Interpreter 

""" 

return 'R Interpreter' 

 

def __reduce__(self): 

""" 

Used in serializing an R interface. 

 

EXAMPLES:: 

 

sage: rlr, t = r.__reduce__() 

sage: rlr(*t) 

R Interpreter 

""" 

return reduce_load_R, tuple([]) 

 

def __getattr__(self, attrname): 

""" 

Called when you get an attribute of the R interface. This 

manufactures an R function, which is a Python function that 

can then be called with various inputs. 

 

EXAMPLES:: 

 

sage: c = r.c; c 

c 

sage: type(c) 

<class 'sage.interfaces.r.RFunction'> 

""" 

if attrname[:1] == "_": 

raise AttributeError 

return RFunction(self, attrname) 

 

 

def _quit_string(self): 

r""" 

Return the string that when typed into R causes the R 

interpreter to exit. 

 

EXAMPLES:: 

 

sage: r._quit_string() 

'quit(save="no")' 

""" 

return 'quit(save="no")' 

 

def _read_in_file_command(self, filename): 

r""" 

Return the R command (as a string) to read in a file named 

filename into the R interpreter. 

 

EXAMPLES:: 

 

sage: r._read_in_file_command('file.txt') 

'file=file("file.txt",open="r")\nsource(file)' 

""" 

return 'file=file("%s",open="r")\nsource(file)'%filename 

 

def read(self, filename): 

r""" 

Read filename into the R interpreter by calling R's source function on a 

read-only file connection. 

 

EXAMPLES:: 

 

sage: filename = tmp_filename() 

sage: f = open(filename, 'w') 

sage: _ = f.write('a <- 2+2\n') 

sage: f.close() 

sage: r.read(filename) 

sage: r.get('a') 

'[1] 4' 

""" 

self.eval( self._read_in_file_command(filename) ) 

 

def _install_hints(self): 

""" 

EXAMPLES:: 

 

sage: print(r._install_hints()) 

R is currently installed with Sage. 

""" 

return "R is currently installed with Sage.\n" 

 

def _source(self, s): 

""" 

Returns the source code of an R function as a string. 

 

INPUT: 

 

- s -- the name of the function as a string 

 

EXAMPLES:: 

 

sage: print(r._source("c")) 

function (...) .Primitive("c") 

""" 

if s[-2:] == "()": 

s = s[-2:] 

return self.eval('%s'%s) 

 

def source(self, s): 

""" 

Display the R source (if possible) about the function named s. 

 

INPUT: 

 

- s -- a string representing the function whose source code you want to see 

 

OUTPUT: string -- source code 

 

EXAMPLES:: 

 

sage: print(r.source("c")) 

function (...) .Primitive("c") 

""" 

return self._source(s) 

 

def version(self): 

""" 

Return the version of R currently running. 

 

OUTPUT: tuple of ints; string 

 

EXAMPLES:: 

 

sage: r.version() # not tested 

((3, 0, 1), 'R version 3.0.1 (2013-05-16)') 

sage: rint, rstr = r.version() 

sage: rint[0] >= 3 

True 

sage: rstr.startswith('R version') 

True 

""" 

major_re = re.compile('^major\s*(\d.*?)$', re.M) 

minor_re = re.compile('^minor\s*(\d.*?)$', re.M) 

version_string_re = re.compile('^version.string\s*(R.*?)$', re.M) 

 

s = self.eval('version') 

 

major = int( major_re.findall(s)[0].strip() ) 

minor = tuple(int(i) for i in minor_re.findall(s)[0].strip().split(".") ) 

version_string = version_string_re.findall(s)[0].strip() 

 

return ( (major,) + minor, version_string ) 

 

def library(self, library_name): 

""" 

Load the library library_name into the R interpreter. 

 

This function raises an ImportError if the given library 

is not known. 

 

INPUT: 

 

- library_name -- string 

 

EXAMPLES:: 

 

sage: r.library('grid') 

sage: 'grid' in r.eval('(.packages())') 

True 

sage: r.library('foobar') 

Traceback (most recent call last): 

... 

ImportError: ... 

""" 

ret = self.eval('require("%s")' % library_name) 

try: 

ret = ret.decode('utf-8') 

except UnicodeDecodeError: 

ret = ret.decode('latin-1') 

# try hard to parse the message string in a locale-independent way 

if ' library(' in ret: # locale-independent key-word 

raise ImportError("%s"%ret) 

else: 

try: 

# We need to rebuild keywords! 

del self.__tab_completion 

except AttributeError: 

pass 

self._tab_completion(verbose=False, use_disk_cache=False) 

 

require = library #overwrites require 

 

def available_packages(self): 

""" 

Returns a list of all available R package names. 

 

This list is not necessarily sorted. 

 

OUTPUT: list of strings 

 

.. note:: 

 

This requires an internet connection. The CRAN server is 

that is checked is defined at the top of sage/interfaces/r.py. 

 

EXAMPLES:: 

 

sage: ap = r.available_packages() # optional - internet 

sage: len(ap) > 20 # optional - internet 

True 

""" 

p = self.new('available.packages("%s/src/contrib")'%RRepositoryURL) 

s = str(p).splitlines()[1:] 

v = [x.split()[0].strip("'") for x in s] 

return v 

#The following was more structural, but breaks on my machine. (stein) 

#p = p._sage_() 

#s = p['_Dim'][0] 

#l = [[p['DATA'][i],p['DATA'][s+1+i]] for i in range(0,s)] 

#return l 

 

def _object_class(self): 

""" 

Return the underlying class of elements of the R interface object. 

 

OUTPUT: a Python class 

 

EXAMPLES:: 

 

sage: r._object_class() 

<class 'sage.interfaces.r.RElement'> 

""" 

return RElement 

 

def _true_symbol(self): 

""" 

Return the symbol that represents True in R. 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: r._true_symbol() 

'[1] TRUE' 

 

This is used behinds the scenes to implement comparison:: 

 

sage: r('1') == r('1') 

[1] TRUE 

sage: r('1') == r('2') 

[1] FALSE 

""" 

# return the string rep of truth, i.e., what the system outputs 

# when you type 1==1. 

return "[1] TRUE" 

 

def _false_symbol(self): 

""" 

Return the symbol that represents True in R. 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: r._false_symbol() 

'[1] FALSE' 

""" 

# return the string rep of false, i.e., what the system outputs 

# when you type 1==2. 

return "[1] FALSE" 

 

def _equality_symbol(self): 

""" 

EXAMPLES:: 

 

sage: r._equality_symbol() 

'==' 

""" 

# return the symbol for checking equality, e.g., == or eq. 

return "==" 

 

def help(self, command): 

""" 

Returns help string for a given command. 

 

INPUT: 

- command -- a string 

 

OUTPUT: HelpExpression -- a subclass of string whose __repr__ method is __str__, so it prints nicely 

 

EXAMPLES:: 

 

sage: r.help('c') 

c package:base R Documentation 

... 

 

.. note:: 

 

This is similar to typing r.command?. 

""" 

s = self.eval('help("%s")'%command).strip() # ?cmd is only an unsafe shortcut 

import sage.plot.plot 

if sage.plot.plot.EMBEDDED_MODE: 

s = s.replace('_\x08','') 

return HelpExpression(s) 

 

def _assign_symbol(self): 

""" 

Return the symbol used in R for assignment, which is ' <- '. 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: r._assign_symbol() 

' <- ' 

""" 

return " <- " 

 

def _left_list_delim(self): 

""" 

Return the left delimiter for lists in R, which is 'c(' 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: r._left_list_delim() 

'c(' 

""" 

return "c(" 

 

def _right_list_delim(self): 

""" 

Return the right delimiter for lists in R, which is 'c(' 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: r._right_list_delim() 

')' 

""" 

return ")" 

 

def console(self): 

""" 

Runs the R console as a separate new R process. 

 

EXAMPLES:: 

 

sage: r.console() # not tested 

R version 2.6.1 (2007-11-26) 

Copyright (C) 2007 The R Foundation for Statistical Computing 

ISBN 3-900051-07-0 

... 

""" 

r_console() 

 

def function_call(self, function, args=None, kwds=None): 

""" 

Return the result of calling an R function, with given args and keyword args. 

 

OUTPUT: RElement -- an object in R 

 

EXAMPLES:: 

 

sage: r.function_call('length', args=[ [1,2,3] ]) 

[1] 3 

""" 

args, kwds = self._convert_args_kwds(args, kwds) 

self._check_valid_function_name(function) 

return self.new("%s(%s)"%(function, ",".join([s.name() for s in args] + 

[self._sage_to_r_name(key)+'='+kwds[key].name() for key in kwds ] ))) 

 

def call(self, function_name, *args, **kwds): 

r""" 

This is an alias for :meth:`function_call`. 

 

EXAMPLES:: 

 

sage: r.call('length', [1,2,3]) 

[1] 3 

""" 

return self.function_call(function_name, args=args, kwds=kwds) 

 

def _an_element_impl(self): 

""" 

Returns an element belonging to the R interpreter. This is used 

behind the scenes when doing things like comparisons, etc. 

 

OUTPUT: RElement -- an R element. 

 

EXAMPLES:: 

 

sage: r._an_element_impl() 

[1] 0 

sage: type(_) 

<class 'sage.interfaces.r.RElement'> 

""" 

return self(0) 

 

def set(self, var, value): 

""" 

Set the variable var in R to what the string value evaluates to in R. 

 

INPUT: 

 

- var -- a string 

- value -- a string 

 

EXAMPLES:: 

 

sage: r.set('a', '2 + 3') 

sage: r.get('a') 

'[1] 5' 

""" 

cmd = '%s <- %s'%(var,value) 

out = self.eval(cmd) 

if out.find("error") != -1: 

raise TypeError("Error executing code in R\nCODE:\n\t%s\nR ERROR:\n\t%s"%(cmd, out)) 

 

def get(self, var): 

""" 

Returns the string representation of the variable var. 

 

INPUT: 

 

- var -- a string 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: r.set('a', 2) 

sage: r.get('a') 

'[1] 2' 

""" 

s = self.eval('%s'%var) 

#return self._remove_indices_re.sub("", s).strip() 

return s 

 

def na(self): 

""" 

Returns the NA in R. 

 

OUTPUT: RElement -- an element of R 

 

EXAMPLES:: 

 

sage: r.na() 

[1] NA 

""" 

return self('NA') 

 

def completions(self, s): 

""" 

Return all commands names that complete the command starting with the 

string s. This is like typing s[Ctrl-T] in the R interpreter. 

 

INPUT: 

 

- s -- string 

 

OUTPUT: list -- a list of strings 

 

EXAMPLES:: 

 

sage: dummy = r._tab_completion(use_disk_cache=False) #clean doctest 

sage: r.completions('tes') 

['testInheritedMethods', 'testPlatformEquivalence', 'testVirtual'] 

""" 

return [name for name in self._tab_completion() if name[:len(s)] == s] 

 

def _commands(self): 

""" 

Return list of all commands defined in R. 

 

OUTPUT: list -- a sorted list of strings 

 

EXAMPLES:: 

 

sage: l = r._commands() 

sage: 'AIC' in l 

True 

sage: len(l) > 200 

True 

""" 

v = RBaseCommands 

 

ll = self.eval('dput(search())') # loaded libs 

ll = self.convert_r_list(ll) 

 

for lib in ll: 

if lib in RFilteredPackages: 

continue 

 

if lib.find("package:") != 0: 

continue #only packages 

 

raw = self.eval('dput(objects("%s"))'%lib) 

raw = self.convert_r_list(raw) 

raw = [x.replace(".","_") for x in raw] 

 

#TODO are there others? many of them are shortcuts or 

#should be done on another level, like selections in lists 

#instead of calling obj.[[( fun-args) or other crazy stuff like that 

 

#TODO further filtering, check if strings are now 

#really functions, in R: exists(s, mode = "function")) 

# (apply to vector with sapply(vec,func)) 

 

#filter only python compatible identifiers 

valid = re.compile('[^a-zA-Z0-9_]+') 

raw = [x for x in raw if valid.search(x) is None] 

v += raw 

 

v.sort() 

return v 

 

def _tab_completion(self, verbose=True, use_disk_cache=True): 

""" 

Return list of all R functions. 

 

INPUT: 

 

- verbose -- bool (default: True); if True, display debugging information 

- use_disk_cache -- bool (default: True); if True, use the disk cache of 

tab completions to save time. 

 

OUTPUT: list -- list of string 

 

EXAMPLES:: 

 

sage: t = r._tab_completion(verbose=False) 

sage: len(t) > 200 

True 

""" 

try: 

return self.__tab_completion 

except AttributeError: 

import sage.misc.persist 

if use_disk_cache: 

try: 

self.__tab_completion = sage.misc.persist.load(COMMANDS_CACHE) 

return self.__tab_completion 

except IOError: 

pass 

if verbose and use_disk_cache: 

print("\nBuilding R command completion list (this takes") 

print("a few seconds only the first time you do it).") 

print("To force rebuild later, delete %s." % COMMANDS_CACHE) 

v = self._commands() 

self.__tab_completion = v 

if len(v) > 200 and use_disk_cache: 

sage.misc.persist.save(v, COMMANDS_CACHE) 

return v 

 

def plot(self, *args, **kwds): 

""" 

The R plot function. Type r.help('plot') for much more extensive 

documentation about this function. See also below for a brief 

introduction to more plotting with R. 

 

If one simply wants to view an R graphic, using this function is 

is sufficient (because it calls dev.off() to turn off the device). 

 

However, if one wants to save the graphic to a specific file, it 

should be used as in the example below to write the output. 

 

EXAMPLES: 

 

This example saves a plot to the standard R output, usually 

a filename like ``Rplot001.png`` - from the command line, in 

the current directory, and in the cell directory in the notebook:: 

 

sage: d=r.setwd('"%s"'%SAGE_TMP) # for doctesting only; ignore if you are trying this; 

sage: r.plot("1:10") # optional -- rgraphics 

null device 

1 

 

To save to a specific file name, one should use :meth:`png` to set 

the output device to that file. If this is done in the notebook, it 

must be done in the same cell as the plot itself:: 

 

sage: filename = tmp_filename() + '.png' 

sage: r.png(filename='"%s"'%filename) # Note the double quotes in single quotes!; optional -- rgraphics 

NULL 

sage: x = r([1,2,3]) 

sage: y = r([4,5,6]) 

sage: r.plot(x,y) # optional -- rgraphics 

null device 

1 

sage: import os; os.unlink(filename) # For doctesting, we remove the file; optional -- rgraphics 

 

Please note that for more extensive use of R's plotting 

capabilities (such as the lattices package), it is advisable 

to either use an interactive plotting device or to use the 

notebook. The following examples are not tested, because they 

differ depending on operating system:: 

 

sage: r.X11() # not tested - opens interactive device on systems with X11 support 

sage: r.quartz() # not tested - opens interactive device on OSX 

sage: r.hist("rnorm(100)") # not tested - makes a plot 

sage: r.library("lattice") # not tested - loads R lattice plotting package 

sage: r.histogram(x = "~ wt | cyl", data="mtcars") # not tested - makes a lattice plot 

sage: r.dev_off() # not tested, turns off the interactive viewer 

 

In the notebook, one can use r.png() to open the device, but 

would need to use the following since R lattice graphics do 

not automatically print away from the command line:: 

 

sage: filename = tmp_filename() + '.png' # Not needed in notebook, used for doctesting 

sage: r.png(filename='"%s"'%filename) # filename not needed in notebook, used for doctesting; optional -- rgraphics 

NULL 

sage: r.library("lattice") 

sage: r("print(histogram(~wt | cyl, data=mtcars))") # plot should appear; optional -- rgraphics 

sage: import os; os.unlink(filename) # We remove the file for doctesting, not needed in notebook; optional -- rgraphics 

""" 

# We have to define this to override the plot function defined in the 

# superclass. 

from sage.server.support import EMBEDDED_MODE 

if EMBEDDED_MODE: 

self.setwd('"%s"'%os.path.abspath('.')) 

RFunction(self, 'plot')(*args, **kwds) 

return RFunction(self, 'dev.off')() 

 

def _strip_prompt(self, code): 

""" 

Remove the standard R prompt from the beginning of lines in code. 

 

INPUT: 

 

- code -- a string 

 

OUTPUT: a string 

 

EXAMPLES:: 

 

sage: s = '> a <- 2\n> b <- 3' 

sage: r._strip_prompt(s) 

' a <- 2\n b <- 3' 

""" 

return prompt_re.sub("", code) 

 

def eval(self, code, globals=None, locals=None, synchronize=True, *args, **kwds): 

""" 

Evaluates a command inside the R interpreter and returns the output 

as a string. 

 

EXAMPLES:: 

 

sage: r.eval('1+1') 

'[1] 2' 

""" 

# TODO split code at ";" outside of quotes and send them as individual 

# lines without ";". 

return Expect.eval(self, code, synchronize=synchronize, *args, **kwds) 

 

def _r_to_sage_name(self, s): 

""" 

Returns a Sage/Python identifier from an R one. This involves 

replacing periods with underscores, <- with __, and prepending 

_ in front of Python keywords. 

 

INPUT: 

 

- s -- a string 

 

OUTPUT: a string 

 

EXAMPLES:: 

 

sage: f = r._r_to_sage_name 

sage: f('t.test') 

't_test' 

sage: f('attr<-') 

'attr__' 

sage: f('parent.env<-') 

'parent_env__' 

sage: f('class') 

'class_' 

""" 

from keyword import iskeyword 

s = s.replace('.', '_') 

s = s.replace('<-', '__') 

if iskeyword(s): 

s += '_' 

return s 

 

def _sage_to_r_name(self, s): 

r""" 

The reverse of :meth:`_r_to_sage_name`. See the docs for that method. 

 

EXAMPLES:: 

 

sage: f = r._sage_to_r_name 

sage: f('t_test') 

't.test' 

sage: f('attr__') 

'attr<-' 

sage: f('parent_env__') 

'parent.env<-' 

sage: r._r_to_sage_name(f('parent_env__')) 

'parent_env__' 

sage: f('class_') 

'class' 

""" 

if len(s) > 1 and s[-2:] == "__": 

s = s[:-2] + '<-' 

if len(s) > 0 and s[-1] == '_': 

s = s[:-1] 

s = s.replace('_', '.') 

return s 

 

def __getitem__(self, s): 

""" 

Returns the RFunction with name s. 

 

INPUT: 

 

- s -- a string 

OUTPUT: RFunction -- the R function that in R has name s 

 

EXAMPLES:: 

 

sage: r['as.data.frame'] 

as.data.frame 

sage: r['print'] 

print 

""" 

return RFunction(self, s, r_name=True) 

 

def chdir(self, dir): 

""" 

Changes the working directory to ``dir`` 

 

INPUT: 

 

- ``dir`` -- the directory to change to. 

 

EXAMPLES:: 

 

sage: import tempfile 

sage: tmpdir = tempfile.mkdtemp() 

sage: r.chdir(tmpdir) 

 

Check that ``tmpdir`` and ``r.getwd()`` refer to the same 

directory. We need to use ``realpath()`` in case ``$TMPDIR`` 

(by default ``/tmp``) is a symbolic link (see :trac:`10264`). 

 

:: 

 

sage: os.path.realpath(tmpdir) == sageobj(r.getwd()) # known bug (trac #9970) 

True 

""" 

self.execute('setwd(%r)' % dir) 

 

 

# patterns for _sage_() 

rel_re_param = re.compile('\s([\w\.]+)\s=') 

rel_re_range = re.compile('([\d]+):([\d]+)') 

rel_re_integer = re.compile('([^\d])([\d]+)L') 

rel_re_terms = re.compile('terms\s*=\s*(.*?),') 

rel_re_call = re.compile('call\s*=\s*(.*?)\),') 

 

 

@instancedoc 

class RElement(ExtraTabCompletion, ExpectElement): 

 

def _tab_completion(self): 

""" 

Return a list of all methods of this object. 

 

.. note:: 

 

Currently returns all R commands. 

 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: t = a._tab_completion() 

sage: len(t) > 200 

True 

""" 

# TODO: rewrite it, just take methods(class=class(self)) 

return self.parent()._tab_completion() 

 

def tilde(self, x): 

""" 

The tilde regression operator in R. 

 

EXAMPLES:: 

 

sage: x = r([1,2,3,4,5]) 

sage: y = r([3,5,7,9,11]) 

sage: a = r.lm( y.tilde(x) ) # lm( y ~ x ) 

sage: d = a._sage_() 

sage: d['DATA']['coefficients']['DATA'][1] 

2 

""" 

par = self.parent() 

rx = par(x) 

return par.new("%s ~ %s" % (self.name(), rx.name())) 

 

stat_model = tilde 

 

def __len__(self): 

""" 

Return the length of this object. 

 

OUTPUT: integer 

 

EXAMPLES:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: len(x) 

5 

""" 

return int(self.parent().eval('dput(length(%s))'%self.name())[:-1] ) 

 

def __getattr__(self, attrname): 

""" 

Return attribute of this object, which is an R function with this object 

as the first input. 

 

INPUT: 

 

- attrname -- string 

 

OUTPUT: RFunctionElement 

 

EXAMPLES:: 

 

sage: x = r([1,2,3]) 

sage: length = x.length 

sage: type(length) 

<class 'sage.interfaces.r.RFunctionElement'> 

sage: length() 

[1] 3 

""" 

self._check_valid() 

if attrname[:1] == "_": 

raise AttributeError 

return RFunctionElement(self, attrname) 

 

def __getitem__(self, n): 

""" 

Return element(s) of self. 

 

INPUT: 

 

- n -- an integer, a tuple, a string that makes sense to R, or an RElement 

 

OUTPUT: RElement 

 

EXAMPLES:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x[0] 

numeric(0) 

sage: x[1] 

[1] 10.4 

sage: x[-1] 

[1] 5.6 3.1 6.4 21.7 

sage: x[-2] 

[1] 10.4 3.1 6.4 21.7 

sage: x[-3] 

[1] 10.4 5.6 6.4 21.7 

sage: x['c(2,3)'] 

[1] 5.6 3.1 

sage: key = r.c(2,3) 

sage: x[key] 

[1] 5.6 3.1 

sage: m = r.array('1:3',r.c(2,4,2)) 

sage: m 

, , 1 

[,1] [,2] [,3] [,4] 

[1,] 1 3 2 1 

[2,] 2 1 3 2 

, , 2 

[,1] [,2] [,3] [,4] 

[1,] 3 2 1 3 

[2,] 1 3 2 1 

sage: m[1,2,2] 

[1] 2 

sage: m[1,r.c(1,2),1] 

[1] 1 3 

""" 

P = self._check_valid() 

if isinstance(n, six.string_types): 

n = n.replace('self', self._name) 

return P.new('%s[%s]'%(self._name, n)) 

elif parent(n) is P: # the key is RElement itself 

return P.new('%s[%s]'%(self._name, n.name())) 

elif not isinstance(n,tuple): 

return P.new('%s[%s]'%(self._name, n)) 

else: 

L = [] 

for i in range(len(n)): 

if parent(n[i]) is P: 

L.append(n[i].name()) 

else: 

L.append(str(n[i])) 

return P.new('%s[%s]'%(self._name, ','.join(L))) 

 

def __bool__(self): 

""" 

Implements bool(self). 

 

.. note:: 

 

bool(self) will only return True if self == 0 contains a FALSE in its representation. 

 

EXAMPLES:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: bool(x) 

True 

sage: y = r([0,0,0,0]) 

sage: bool(y) 

False 

sage: bool(r(0)) 

False 

sage: bool(r(1)) 

True 

""" 

return "FALSE" in repr(self==0) 

 

__nonzero__ = __bool__ 

 

def _comparison(self, other, symbol): 

""" 

Used to implement comparison of two objects. 

 

INPUT: 

 

- other -- RElement 

- symbol -- string 

 

OUTPUT: RElement -- output is an R element; not a bool! 

 

TESTS:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x._comparison(10.4, "==") 

[1] TRUE FALSE FALSE FALSE FALSE 

""" 

P = self.parent() 

other = P(other) 

return P('%s %s %s'%(self.name(), symbol, other.name())) 

 

def __eq__(self, other): 

""" 

Equality testing term by term. 

 

INPUT: 

 

- other -- RElement 

 

OUTPUT: RElement -- an R element; not a bool! 

 

EXAMPLES: 

 

Notice that comparison is term by term and returns an R element. :: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x == 10.4 

[1] TRUE FALSE FALSE FALSE FALSE 

""" 

return self._comparison(other, "==") 

 

def __lt__(self, other): 

""" 

Less than testing term by term. 

 

INPUT: 

 

- other -- RElement 

 

OUTPUT: RElement -- an R element; not a bool! 

 

EXAMPLES: 

 

Notice that comparison is term by term and returns an R element. :: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x < 7 

[1] FALSE TRUE TRUE TRUE FALSE 

""" 

return self._comparison(other, "<") 

 

def __gt__(self, other): 

""" 

Greater than testing term by term. 

 

INPUT: 

 

- other -- RElement 

 

OUTPUT: RElement -- an R element; not a bool! 

 

EXAMPLES: 

 

Notice that comparison is term by term and returns an R element. :: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x > 8 

[1] TRUE FALSE FALSE FALSE TRUE 

""" 

return self._comparison(other, ">") 

 

def __le__(self, other): 

""" 

Less than or equal testing term by term. 

 

INPUT: 

 

- other -- RElement 

 

OUTPUT: RElement -- an R element; not a bool! 

 

EXAMPLES:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x <= 10.4 

[1] TRUE TRUE TRUE TRUE FALSE 

""" 

return self._comparison(other, "<=") 

 

def __ge__(self, other): 

""" 

Greater than or equal testing term by term. 

 

INPUT: 

 

- other -- RElement 

 

OUTPUT: RElement -- an R element; not a bool! 

 

EXAMPLES:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x >= 10.4 

[1] TRUE FALSE FALSE FALSE TRUE 

""" 

return self._comparison(other, ">=") 

 

def __ne__(self, other): 

""" 

Not equal testing term by term. 

 

INPUT: 

 

- other -- RElement 

 

OUTPUT: RElement -- an R element; not a bool! 

 

EXAMPLES:: 

 

sage: x = r([10.4,5.6,3.1,6.4,21.7]) 

sage: x != 10.4 

[1] FALSE TRUE TRUE TRUE TRUE 

 

""" 

return self._comparison(other, "!=") 

 

def __cmp__(self, other): 

r""" 

Return 0, 1, or -1 depending on how self and other compare. 

 

This is *not* called by the comparison operators, which 

do term-by-term comparison and return R elements. 

 

INPUT: 

 

- self, other -- R elements 

 

OUTPUT: 0, 1, or -1 

 

EXAMPLES:: 

 

sage: one = r(1) 

sage: two = r(2) 

sage: one.__cmp__(one) 

0 

sage: one.__cmp__(two) 

-1 

sage: two.__cmp__(one) 

1 

""" 

P = self.parent() 

if P.eval("%s %s %s" % (self.name(), P._equality_symbol(), 

other.name())) == P._true_symbol(): 

return 0 

elif P.eval("%s %s %s" % (self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol(): 

return -1 

elif P.eval("%s %s %s" % (self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): 

return 1 

else: 

return -1 # everything is supposed to be comparable in Python, so we define 

# the comparison thus when no comparable in interfaced system. 

 

 

def dot_product(self, other): 

""" 

Implements the notation self . other. 

 

INPUT: 

 

- self, other -- R elements 

 

OUTPUT: R element 

 

EXAMPLES:: 

 

sage: c = r.c(1,2,3,4) 

sage: c.dot_product(c.t()) 

[,1] [,2] [,3] [,4] 

[1,] 1 2 3 4 

[2,] 2 4 6 8 

[3,] 3 6 9 12 

[4,] 4 8 12 16 

 

sage: v = r([3,-1,8]) 

sage: v.dot_product(v) 

[,1] 

[1,] 74 

""" 

P = self._check_valid() 

Q = P(other) 

# the R operator is %*% for matrix multiplication 

return P('%s %%*%% %s'%(self.name(), Q.name())) 

 

def _subs_dots(self, x): 

r""" 

Replace dots by underscores; used internally to implement 

conversation from R expression to Sage objects. 

 

INPUT: 

 

- x -- regular expression match: ``<type '_sre.SRE_Match'>`` 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: import re 

sage: a = r([1,2,3]) 

sage: rel_re_param = re.compile(r'\s([\w\.]+)\s=') 

sage: rel_re_param.sub(a._subs_dots, ' test.test =') 

' test_test =' 

""" 

return x.group().replace('.','_') 

 

def _subs_range(self, x): 

r""" 

Change endpoints of ranges. This is used internally in the 

code for converting R expressions to Sage objects. 

 

INPUT: 

 

- x -- regular expression match: ``<type '_sre.SRE_Match'>`` 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: import re 

sage: a = r([1,2,3]) 

sage: rel_re_range = re.compile(r'([\d]+):([\d]+)') 

sage: rel_re_range.sub(a._subs_range, ' 1:10') 

' range(1,11)' 

""" 

g = x.groups() 

g1 = int(g[1]) + 1 

return 'range(%s,%s)' % (g[0], g1) 

 

def _subs_integer(self, x): 

r""" 

Replaces strings like 'dL' with 'Integer(d)' where d is some 

integer. This is used internally in the code for converting R 

expressions to Sage objects. 

 

EXAMPLES:: 

 

sage: import re 

sage: a = r([1,2,3]) 

sage: rel_re_integer = re.compile(r'([^\d])([\d]+)L') 

sage: rel_re_integer.sub(a._subs_integer, ' 1L 2L') 

' Integer(1) Integer(2)' 

sage: rel_re_integer.sub(a._subs_integer, '1L 2L') 

'1L Integer(2)' 

 

""" 

return '%sInteger(%s)'%x.groups() 

 

def _convert_nested_r_list(self, exp): 

""" 

Converts a string representing a (possibly) nested list in R 

to a (possibly) nested Python list. This is used internally 

in the code for converting R expressions to Sage objects. 

 

INPUT: 

 

- exp -- a string 

 

OUTPUT: a string 

 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: s = 'c(1, 2, 3)' 

sage: a._convert_nested_r_list(s) 

'[1, 2, 3]' 

""" 

from re import compile as re_compile 

from re import split as re_split 

splt = re_compile('(c\(|\(|\))') # c( or ( or ) 

lvl = 0 

ret = [] 

for token in re_split(splt, exp): 

if token == 'c(': 

ret.append('[') 

lvl += 1 

elif token == '(': 

ret.append(token) 

if lvl > 0 : lvl += 1 

elif token == ')': 

if lvl == 1: 

ret.append(']') 

lvl -= 1 

else: 

ret.append(token) 

if lvl > 0: 

lvl -= 1 

else: 

ret.append(token) 

 

return ''.join(ret) 

 

 

def _r_list(self, *args, **kwds): 

""" 

This is used internally in the code for converting R 

expressions to Sage objects. 

 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: list(sorted(a._r_list(1,2,3,k=5).items())) 

[('#0', 1), ('#1', 2), ('#2', 3), ('k', 5)] 

""" 

ret = dict(kwds) 

i = 0 

for k in args: 

ret['#%s'%i] = k 

i += 1 

return ret 

 

def _r_structure(self, __DATA__, **kwds): 

""" 

This is used internally in the code for converting R 

expressions to Sage objects. 

 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: d = a._r_structure('data', a=1, b=2) 

sage: list(sorted(d.items())) 

[('DATA', 'data'), ('a', 1), ('b', 2)] 

sage: a._r_structure([1,2,3,4], _Dim=(2,2)) 

[1 3] 

[2 4] 

 

""" 

if '_Dim' in kwds: #we have a matrix 

# TODO what about more than 2 dimensions? 

# additional checks!! 

try: 

from sage.matrix.constructor import matrix 

d = kwds.get('_Dim') 

# TODO: higher dimensions? happens often in statistics 

if len(d) != 2: 

raise TypeError 

#since R does it the other way round, we assign 

#transposed and then transpose the matrix :) 

m = matrix(d[1], d[0], [i for i in __DATA__]) 

return m.transpose() 

except TypeError: 

pass 

d = dict(DATA=__DATA__) 

d.update(kwds) 

return d 

 

def _sage_(self): 

r""" 

Returns Sage representation of the R object. 

 

R objects are basic C structures, of different kind, that can 

be stacked together. This is similar to Python lists with 

variable objects, including lists of lists. If R lists have 

names, they are translated to a Python dictionary, with anonymous 

list entries called ``#{number}``. 

 

OUTPUT: object -- Python object 

 

EXAMPLES:: 

 

sage: rs = r.summary(r.c(1,4,3,4,3,2,5,1)) 

sage: d = rs._sage_() 

sage: list(sorted(d.items())) 

[('DATA', [1, 1.75, 3, 2.875, 4, 5]), 

('_Names', ['Min.', '1st Qu.', 'Median', 'Mean', '3rd Qu.', 'Max.']), 

('_r_class', ['summaryDefault', 'table'])] 

""" 

self._check_valid() 

P = self.parent() 

 

# This is the core of the trick: using dput 

# dput prints out the internal structure of R's data elements 

# options via .deparseOpts(control=...) 

# TODO: dput also works with a file, if things get huge! 

# [[However, using a file for output often isn't necessary 

# since pipe buffering works pretty well for output. 

# That said, benchmark this. -- William Stein]] 

exp = P.eval('dput(%s)'%self.name()) 

 

# Preprocess expression 

# example what this could be: 

# structure(list(statistic = structure(0.233549683248457, .Names = "t"), 

# parameter = structure(5.58461538461538, .Names = "df"), p.value = 0.823657802106985, 

# conf.int = structure(c(-2.41722062247400, 2.91722062247400 

# ), conf.level = 0.95), estimate = structure(c(2.75, 2.5), .Names = c("mean of x", 

# "mean of y")), null.value = structure(0, .Names = "difference in means"), 

# alternative = "two.sided", method = "Welch Two Sample t-test", 

# data.name = "c(1, 2, 3, 5) and c(1, 2, 3, 4)"), .Names = c("statistic", 

# "parameter", "p.value", "conf.int", "estimate", "null.value", 

# "alternative", "method", "data.name"), class = "htest") 

 

# R's structure (from help): 

# structure(.Data, ...) 

# .Data: an object which will have various attributes attached to it. 

# ...: attributes, specified in 'tag=value' form, which will be 

# attached to data. 

#For historical reasons (these names are used when deparsing), 

# attributes '".Dim"', '".Dimnames"', '".Names"', '".Tsp"' and 

# '".Label"' are renamed to '"dim"', '"dimnames"', '"names"', 

# '"tsp"' and '"levels"'. 

 

 

 

# we want this in a single line 

exp.replace('\n','') 

exp = "".join(exp.split("\n")) 

 

# python compatible parameters 

exp = rel_re_param.sub(self._subs_dots, exp) 

 

# Rename class since it is a Python keyword 

exp = re.sub(' class = ', ' _r_class = ',exp) 

 

# Change 'structure' to '_r_structure' 

# TODO: check that we are outside of quotes "" 

exp = re.sub(' structure\(', ' _r_structure(', exp) 

exp = re.sub('^structure\(', '_r_structure(', exp) #special case 

 

# Change 'list' to '_r_list' 

exp = re.sub(' list\(', ' _r_list(', exp) 

exp = re.sub('\(list\(', '(_r_list(', exp) 

 

# Change 'a:b' to 'range(a,b+1)' 

exp = rel_re_range.sub(self._subs_range, exp) 

 

# Change 'dL' to 'Integer(d)' 

exp = rel_re_integer.sub(self._subs_integer, exp) 

 

# Wrap the right hand side of terms = ... in quotes since it 

# has a ~ in it. 

exp = rel_re_terms.sub(r'terms = "\1",', exp) 

 

 

# Change call = ..., to call = "...", 

exp = rel_re_call.sub(r'call = "\1",', exp) 

 

# seems to work for 

# rr = r.summary(r.princomp(r.matrix(r.c(1,2,3,4,3,4,1,2,2),4))) 

# rr._sage_() 

# but the call expression get's evaluated. why?!? TODO 

 

 

# translation: 

# c is an ordered list 

# list is a dictionary (where _Names give the entries names. 

# map entries in names to (value, name) in each entry? 

# structure is .. see above .. structure(DATA,**kw) 

# TODO: thinking of just replacing c( with ( to get a long tuple? 

 

 

exp = self._convert_nested_r_list(exp) 

 

# Set up the globals 

globs = {'NA':None, 'NULL':None, 'FALSE':False, 'TRUE':True, 

'_r_list':self._r_list, '_r_structure':self._r_structure, 

'Integer':sage.rings.integer.Integer, 

'character':str} 

 

return eval(exp, globs, globs) 

 

 

def _latex_(self): 

r""" 

Return LaTeX representation of this R object. 

 

This calls the ``latex`` command in R. 

 

OUTPUT: a latex expression (basically a string) 

 

EXAMPLES:: 

 

sage: latex(r(2)) # optional - Hmisc (R package) 

2 

""" 

from sage.misc.latex import LatexExpr 

self._check_valid() 

P = self.parent() 

# latex is in Hmisc, this is currently not part of Sage's R!!! 

try: 

P.library('Hmisc') 

except ImportError: 

raise RuntimeError("The R package 'Hmisc' is required for R to LaTeX conversion, but it is not available.") 

return LatexExpr(P.eval('latex(%s, file="");'%self.name())) 

 

 

@instancedoc 

class RFunctionElement(FunctionElement): 

def __reduce__(self): 

""" 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: a.mean 

mean 

sage: dumps(a.mean) 

Traceback (most recent call last): 

... 

NotImplementedError: pickling of R element methods is not yet supported 

""" 

raise NotImplementedError("pickling of R element methods is not yet supported") 

 

def _instancedoc_(self): 

""" 

Returns the help for self as a string. 

 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: length = a.length 

sage: print(length.__doc__) 

length package:base R Documentation 

... 

<BLANKLINE> 

""" 

M = self._obj.parent() 

return M.help(self._name) 

 

def _sage_src_(self): 

""" 

Returns the source code of self. 

 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: length = a.length 

sage: print(length._sage_src_()) 

function (x) .Primitive("length") 

""" 

M = self._obj.parent() 

return M.source(self._name) 

 

def __call__(self, *args, **kwds): 

""" 

EXAMPLES:: 

 

sage: a = r([1,2,3]) 

sage: length = a.length 

sage: length() 

[1] 3 

""" 

return self._obj.parent().function_call(self._name, args=[self._obj] + list(args), kwds=kwds) 

 

 

@instancedoc 

class RFunction(ExpectFunction): 

def __init__(self, parent, name, r_name=None): 

""" 

A Function in the R interface. 

 

INPUT: 

 

- parent -- the R interface 

- name -- the name of the function for Python 

- r_name -- the name of the function in R itself (which can have dots in it) 

 

EXAMPLES:: 

 

sage: length = r.length 

sage: type(length) 

<class 'sage.interfaces.r.RFunction'> 

sage: loads(dumps(length)) 

length 

""" 

self._parent = parent 

if r_name: 

self._name = name 

else: 

self._name = parent._sage_to_r_name(name) 

 

def __eq__(self, other): 

""" 

EXAMPLES:: 

 

sage: r.mean == loads(dumps(r.mean)) 

True 

sage: r.mean == r.lr 

False 

""" 

return (isinstance(other, RFunction) and 

self._name == other._name) 

 

def __ne__(self, other): 

""" 

EXAMPLES:: 

 

sage: r.mean != loads(dumps(r.mean)) 

False 

sage: r.mean != r.lr 

True 

""" 

return not (self == other) 

 

def _instancedoc_(self): 

""" 

Returns the help for self. 

 

EXAMPLES:: 

 

sage: length = r.length 

sage: print(length.__doc__) 

length package:base R Documentation 

... 

<BLANKLINE> 

""" 

M = self._parent 

return M.help(self._name) 

 

def _sage_src_(self): 

""" 

Returns the source of self. 

 

EXAMPLES:: 

 

sage: length = r.length 

sage: print(length._sage_src_()) 

function (x) .Primitive("length") 

 

""" 

M = self._parent 

return M.source(self._name) 

 

def __call__(self, *args, **kwds): 

""" 

EXAMPLES:: 

 

sage: length = r.length 

sage: length([1,2,3]) 

[1] 3 

""" 

return self._parent.function_call(self._name, args=list(args), kwds=kwds) 

 

def is_RElement(x): 

""" 

Return True if x is an element in an R interface. 

 

INPUT: 

 

- x -- object 

 

OUTPUT: bool 

 

EXAMPLES:: 

 

sage: from sage.interfaces.r import is_RElement 

sage: is_RElement(2) 

False 

sage: is_RElement(r(2)) 

True 

""" 

return isinstance(x, RElement) 

 

# An instance of R 

r = R() 

 

def reduce_load_R(): 

""" 

Used for reconstructing a copy of the R interpreter from a pickle. 

 

EXAMPLES:: 

 

sage: from sage.interfaces.r import reduce_load_R 

sage: reduce_load_R() 

R Interpreter 

""" 

return r 

 

import os 

def r_console(): 

""" 

Spawn a new R command-line session. 

 

EXAMPLES:: 

 

sage: r.console() # not tested 

R version 2.6.1 (2007-11-26) 

Copyright (C) 2007 The R Foundation for Statistical Computing 

ISBN 3-900051-07-0 

... 

""" 

from sage.repl.rich_output.display_manager import get_display_manager 

if not get_display_manager().is_in_terminal(): 

raise RuntimeError('Can use the console only in the terminal. Try %%r magics instead.') 

# This will only spawn local processes 

os.system('R --vanilla') 

 

def r_version(): 

""" 

Return the R version. 

 

EXAMPLES:: 

 

sage: r_version() # not tested 

((3, 0, 1), 'R version 3.0.1 (2013-05-16)') 

sage: rint, rstr = r_version() 

sage: rint[0] >= 3 

True 

sage: rstr.startswith('R version') 

True 

""" 

return r.version() 

 

class HelpExpression(str): 

""" 

Used to improve printing of output of r.help. 

""" 

def __repr__(self): 

""" 

Return string representation of self. 

 

OUTPUT: string 

 

EXAMPLES:: 

 

sage: a = sage.interfaces.r.HelpExpression("This\nis\nR!") 

sage: type(a) 

<class 'sage.interfaces.r.HelpExpression'> 

sage: a 

This 

is 

R! 

""" 

return str(self)