Wednesday, November 2, 2011

Subsetting lists in Python and R

I'm sure these are not the only two approaches:


Python:

a = ["1/fish","1/cat","1/dog","2/mouse"]
#method 1:
filter(lambda w:w[0:2]=='1/',a)
#method 2:
import re
filter(lambda w:re.search('^1/.*', w), a)

R:

a = c("1/fish","1/cat","1/dog","2/mouse")
#method 1
a[sapply(a, substr, 1,2) == "1/"]
#method 2
grep("^1/",a, value=T)

No comments:

Post a Comment