0

As a python user, R has been somewhat intuitive thus far. However, I'm running into a problem with creating a new list from an old one.

Specifically I have a list:

> x
[[1]]
  [1] "Heads" "Tails" "Tails" "Heads" "Tails" "Heads"
  [7] "Tails" "Tails" "Tails" "Heads" "Heads" "Tails"
  ... .... ... etc.

This is length 100. I'd like to loop through this list and create a list y with the values 'Heads' = 1, 'Tails' = -1. My attempt so far:

> for (val in x) {
         ifelse(val == 'Heads', c(y,1), c(y,-1))}

Which appends an empty list y. However, the result is a list of length 2. Can anybody help me here?

Datdat
  • 33
  • 2
  • You want a new list of two columns with the first one having the ``Heads`` and ``Tails`` value and the second column having ``1`` and ``-1`` respectively? – Gainz Sep 25 '19 at 14:34
  • 1
    Can you make your example input reproducible? https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – zx8754 Sep 25 '19 at 14:35
  • What is the output of length(x) and lengths(x) ? – zx8754 Sep 25 '19 at 14:36
  • You need to save the results of `ifelse` to something. Probably `y`... `y <- ifelse(...)` – cory Sep 25 '19 at 15:41

2 Answers2

1

You can use a named vector:

c("Heads" = 1, "Tails" = -1)[x[[1]]]
> Heads Tails Tails Heads Tails Heads Tails Tails Tails Heads Heads Tails 
      1    -1    -1     1    -1     1    -1    -1    -1     1     1    -1 

Or to get a vector using boolean conversion to numeric (elegant but maybe not the most efficient):

(x[[1]] == "Heads") * 2 - 1
> [1]  1 -1 -1  1 -1  1 -1 -1 -1  1  1 -1
Clemsang
  • 5,053
  • 3
  • 23
  • 41
0

As far as I understand, you have a nested list with two unique values. You can use lapply for that:

x <- list(list("Heads","Tails","Heads"),list("Heads","Tails","Tails"))
lapply(x, function(x){y <- ifelse(x == "Heads", 1, -1); names(y) <- x; y})

# [[1]]
# Heads Tails Heads 
# 1    -1     1 
# 
# [[2]]
# Heads Tails Tails 
# 1    -1    -1

or, if you don't need the names, use rapply:

x <- list(list("Heads","Tails","Heads"),list("Heads","Tails","Tails"))
rapply(x, function(x){ifelse(x == "Heads", 1, -1)})
slava-kohut
  • 4,203
  • 1
  • 7
  • 24