Reputation: 211
I have lists like this:
Action=[A,B,C,D,E,F,G,H,I]
a=[A,B,E,I]
b=[C,D,F,G,H]
So, I want to get the action vector corresponding to a and b, that's mean like this
Action=[a,a,b,b,a,b,b,b,a]
How can I do it in R or python?
Upvotes: 0
Views: 39
Reputation: 26315
In python, you can use a dictionary:
Action = ['A','B','C','D','E','F','G','H','I']
a = ['A','B','E','I']
b = ['C','D','F','G','H']
d = {}
for elem in a:
d[elem] = 'a'
for elem in b:
d[elem] = 'b'
result = [d[action] for action in Action if action in d]
print(result)
Which Outputs:
['a', 'a', 'b', 'b', 'a', 'b', 'b', 'b', 'a']
Upvotes: 0
Reputation: 269694
In R, use ifelse
like this:
ifelse(A %in% a, "a", "b")
## [1] "a" "a" "b" "b" "a" "b" "b" "b" "a"
Upvotes: 0
Reputation: 354
I'm assuming these values are characters.
You could do the following in R
A <- c('A','B','C','D','E','F','G','H','I')
a <- c('A','B','E','I')
b <- c('C','D','F','G','H')
Action <- character(length(A))
Action[which(A %in% a)] <- 'a'
Action[which(A %in% b)] <- 'b'
Action
# [1] "a" "a" "b" "b" "a" "b" "b" "b" "a"
And you could use list comprehension in Python
A = ['A','B','C','D','E','F','G','H','I']
a = ['A','B','E','I']
b = ['C','D','F','G','H']
Action = ['a' if i in a else 'b' if i in b else None for i in Action]
print(Action)
# ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'b', 'a']
Upvotes: 1