or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

environment-management.mdhigh-level-interface.mdindex.mdjupyter-integration.mdlow-level-interface.mdpackage-management.mdtype-conversion.mdvectors-datatypes.md

type-conversion.mddocs/

0

# Type Conversion

1

2

Flexible conversion framework for automatic and manual type conversion between Python and R objects, with support for NumPy, pandas integration, and custom conversion rules.

3

4

## Capabilities

5

6

### Conversion System Core

7

8

The conversion system manages bidirectional type conversion between Python and R objects.

9

10

```python { .api }

11

class Converter:

12

"""

13

Type conversion manager for Python-R object conversion.

14

15

Manages conversion rules and provides context for

16

automatic type conversion between Python and R.

17

"""

18

def py2rpy(self, obj):

19

"""

20

Convert Python object to R object.

21

22

Parameters:

23

- obj: Python object to convert

24

25

Returns:

26

R object equivalent

27

28

Raises:

29

NotImplementedError: If no conversion rule exists

30

"""

31

32

def rpy2py(self, obj):

33

"""

34

Convert R object to Python object.

35

36

Parameters:

37

- obj: R object to convert

38

39

Returns:

40

Python object equivalent

41

42

Raises:

43

NotImplementedError: If no conversion rule exists

44

"""

45

46

def __enter__(self):

47

"""Context manager entry."""

48

49

def __exit__(self, exc_type, exc_val, exc_tb):

50

"""Context manager exit."""

51

52

# Global conversion instances

53

default_converter: Converter # Default conversion rules

54

flatlist_converter: Converter # List-flattening converter

55

```

56

57

### Context Management

58

59

Manage conversion contexts for different conversion behaviors.

60

61

```python { .api }

62

def get_conversion() -> Converter:

63

"""

64

Get current conversion context.

65

66

Returns:

67

Active converter instance

68

"""

69

70

def set_conversion(converter: Converter):

71

"""

72

Set conversion context.

73

74

Parameters:

75

- converter: Converter instance to activate

76

"""

77

78

# Context variable for current converter

79

converter_ctx: Any

80

```

81

82

### Direct Conversion Functions

83

84

Standalone functions for explicit type conversion.

85

86

```python { .api }

87

def py2ro(obj):

88

"""

89

Convert Python object to R object using current converter.

90

91

Parameters:

92

- obj: Python object to convert

93

94

Returns:

95

R object equivalent

96

"""

97

98

def ro2py(obj):

99

"""

100

Convert R object to Python object using current converter.

101

102

Parameters:

103

- obj: R object to convert

104

105

Returns:

106

Python object equivalent

107

"""

108

```

109

110

### NumPy Integration

111

112

Automatic conversion between NumPy arrays and R vectors/matrices.

113

114

```python { .api }

115

# Available in rpy2.robjects.numpy2ri module

116

def activate():

117

"""

118

Activate automatic NumPy conversions.

119

120

Enables bidirectional conversion between:

121

- NumPy arrays ↔ R vectors/matrices

122

- NumPy dtypes ↔ R vector types

123

- NumPy structured arrays ↔ R data frames

124

"""

125

126

def deactivate():

127

"""

128

Deactivate automatic NumPy conversions.

129

130

Returns to default conversion behavior

131

without NumPy-specific rules.

132

"""

133

134

# NumPy conversion context

135

numpy_converter: Converter

136

```

137

138

### Pandas Integration

139

140

Automatic conversion between pandas objects and R data structures.

141

142

```python { .api }

143

# Available in rpy2.robjects.pandas2ri module

144

def activate():

145

"""

146

Activate automatic pandas conversions.

147

148

Enables bidirectional conversion between:

149

- pandas DataFrame ↔ R data.frame

150

- pandas Series ↔ R vectors

151

- pandas Index ↔ R character vectors

152

- pandas Categorical ↔ R factors

153

"""

154

155

def deactivate():

156

"""

157

Deactivate automatic pandas conversions.

158

159

Returns to default conversion behavior

160

without pandas-specific rules.

161

"""

162

163

# Pandas conversion context

164

pandas_converter: Converter

165

```

166

167

### Conversion Utilities

168

169

Helper classes and functions for conversion management.

170

171

```python { .api }

172

class NameClassMap:

173

"""

174

Name to class mapping utility for conversion rules.

175

176

Maps object names or types to specific conversion

177

classes for customized conversion behavior.

178

"""

179

def __init__(self, mapping: dict): ...

180

def __getitem__(self, key): ...

181

def __setitem__(self, key, value): ...

182

```

183

184

### Default Conversions

185

186

Built-in conversion rules between common Python and R types.

187

188

```python { .api }

189

# Python → R conversions

190

# int → IntSexpVector

191

# float → FloatSexpVector

192

# bool → BoolSexpVector

193

# str → StrSexpVector

194

# list → ListSexpVector

195

# dict → ListSexpVector (named)

196

# None → NULL

197

198

# R → Python conversions

199

# IntSexpVector → list of int

200

# FloatSexpVector → list of float

201

# BoolSexpVector → list of bool

202

# StrSexpVector → list of str

203

# ListSexpVector → list or dict

204

# NULL → None

205

```

206

207

### Usage Examples

208

209

```python

210

import rpy2.robjects as ro

211

from rpy2.robjects.conversion import Converter, get_conversion

212

import numpy as np

213

import pandas as pd

214

215

# Basic conversion using default converter

216

python_list = [1, 2, 3, 4, 5]

217

r_vector = ro.conversion.py2rpy(python_list)

218

print(type(r_vector)) # IntVector

219

220

# Convert back to Python

221

back_to_python = ro.conversion.rpy2py(r_vector)

222

print(back_to_python) # [1, 2, 3, 4, 5]

223

224

# Using conversion contexts

225

with ro.conversion.flatlist_converter:

226

# Lists are flattened during conversion

227

nested_list = [[1, 2], [3, 4], [5, 6]]

228

flat_vector = ro.conversion.py2rpy(nested_list)

229

230

# NumPy integration

231

import rpy2.robjects.numpy2ri as numpy2ri

232

233

# Activate NumPy conversions

234

numpy2ri.activate()

235

236

# Convert NumPy array to R

237

numpy_array = np.array([1.1, 2.2, 3.3, 4.4, 5.5])

238

r_vector = ro.conversion.py2rpy(numpy_array)

239

print(type(r_vector)) # FloatVector

240

241

# NumPy matrix to R matrix

242

numpy_matrix = np.array([[1, 2, 3], [4, 5, 6]])

243

r_matrix = ro.conversion.py2rpy(numpy_matrix)

244

print(r_matrix.nrow, r_matrix.ncol) # 2 3

245

246

# Deactivate when done

247

numpy2ri.deactivate()

248

249

# Pandas integration

250

import rpy2.robjects.pandas2ri as pandas2ri

251

252

# Activate pandas conversions

253

pandas2ri.activate()

254

255

# Convert pandas DataFrame to R

256

df = pd.DataFrame({

257

'A': [1, 2, 3, 4, 5],

258

'B': [1.1, 2.2, 3.3, 4.4, 5.5],

259

'C': ['a', 'b', 'c', 'd', 'e']

260

})

261

262

r_dataframe = ro.conversion.py2rpy(df)

263

print(type(r_dataframe)) # DataFrame

264

print(r_dataframe.colnames) # ['A', 'B', 'C']

265

266

# Convert pandas Series to R vector

267

series = pd.Series([10, 20, 30, 40, 50])

268

r_series = ro.conversion.py2rpy(series)

269

print(type(r_series)) # IntVector

270

271

# Pandas Categorical to R factor

272

categorical = pd.Categorical(['low', 'medium', 'high', 'low', 'high'])

273

r_factor = ro.conversion.py2rpy(categorical)

274

print(type(r_factor)) # FactorVector

275

276

pandas2ri.deactivate()

277

278

# Custom conversion context

279

class MyConverter(Converter):

280

"""Custom converter with special rules."""

281

def py2rpy(self, obj):

282

if isinstance(obj, str) and obj.startswith('DATE:'):

283

# Convert special date strings to R Date objects

284

date_str = obj[5:] # Remove 'DATE:' prefix

285

return ro.r(f'as.Date("{date_str}")')

286

return super().py2rpy(obj)

287

288

# Use custom converter

289

my_converter = MyConverter()

290

with my_converter:

291

special_date = "DATE:2023-12-25"

292

r_date = ro.conversion.py2rpy(special_date)

293

print(type(r_date)) # R Date object

294

295

# Check current conversion context

296

current_converter = get_conversion()

297

print(f"Current converter: {type(current_converter)}")

298

299

# Manual converter switching

300

from rpy2.robjects.conversion import set_conversion

301

set_conversion(ro.conversion.flatlist_converter)

302

# Now flatlist_converter is active

303

304

# Combined conversions for complex workflows

305

with numpy2ri.converter + pandas2ri.converter:

306

# Both NumPy and pandas conversions active

307

mixed_conversion = True

308

```

309

310

### Advanced Conversion Patterns

311

312

```python

313

# Create converter with specific rules

314

custom_converter = Converter("Custom converter")

315

316

# Add conversion rules (advanced usage)

317

@custom_converter.py2rpy.register

318

def py2rpy_custom_class(obj):

319

if isinstance(obj, MyCustomClass):

320

return convert_to_r_equivalent(obj)

321

return NotImplemented

322

323

# Chaining converters

324

combined = numpy2ri.converter + pandas2ri.converter + custom_converter

325

326

# Temporary conversion override

327

original_converter = get_conversion()

328

try:

329

set_conversion(combined)

330

# Perform conversions with combined rules

331

result = ro.conversion.py2rpy(complex_object)

332

finally:

333

set_conversion(original_converter)

334

```