Python for R Users
Daniel Chen
Instructor
data = [1, 2, 3, 4, 5]
new = []
for x in data:
new.append(x**2)
print(new)
[1, 4, 9, 16, 25]
data = [1, 2, 3, 4, 5]
new = [x**2 for x in data]
print(new)
[1, 4, 9, 16, 25]
data = [1, 2, 3, 4, 5]
new = {}
for x in data:
new[x] = x**2
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
data = [1, 2, 3, 4, 5]
new = {x: x**2 for x in data}
print(new)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
for
loop to iteratesapply
, lapply
, apply
functionsmap
function and apply
methoddef sq(x):
return x**2
l = [1, 2, 3]
for i in l:
print(sq(i))
1
4
9
map(sq, l)
<map at 0x7f41cca38358>
list(map(sq, l))
[1, 4, 9]
Python for R Users