R apply factor objects
I would like to apply
the factor
function over each row of an R
dataframe. So, I'd like to get a array of factor
type objects. However, when I:
apply(df, 1, factor)
I don't get that thing. What am I misunderstanding about apply
or factor
?
data:
dput(df)
structure(list(flip..1. = c("heads", "heads"), flip..2. = c("tails", "heads"), flip..3. = c("heads", "tails"), flip..4. = c("tails", "tails"), flip..5. = c("heads", "tails"), flip..6. = c("tails", "heads"), flip..7. = c("heads", "heads"), flip..8. = c("heads", "tails"), flip..9. = c("tails", "tails"), flip..10. = c("heads", "heads")), class = "data.frame", row.names = c(NA, -2L))
code:
rowwise_factors <- apply(df, 1, factor)
# rowwise_factors seems to be a matrix of characters, or some such, not an array of factor objects.
expected_output:
dput(expected)
list(structure(c(flip..1. = 1L, flip..2. = 2L, flip..3. = 1L, flip..4. = 2L, flip..5. = 1L, flip..6. = 2L, flip..7. = 1L, flip..8. = 1L, flip..9. = 2L, flip..10. = 1L), .Label = c("heads", "tails"), class = "factor"),
structure(c(flip..1. = 1L, flip..2. = 1L, flip..3. = 2L,
flip..4. = 2L, flip..5. = 2L, flip..6. = 1L, flip..7. = 1L,
flip..8. = 2L, flip..9. = 2L, flip..10. = 1L), .Label = c("heads", "tails"), class = "factor"))
What am I misunderstanding here, and also how do I make this work?
W.R.T. CLOSE: these don't answer my question, as I would like to apply this ROW-WISE, not COLUMN-WISE. Simply transposing my data.frame doesn't make the cited solutions work.
This works in R-4.1 and newer, as that is when simplify=
was added to apply(.)
:
apply(df, 1, factor, levels = c("heads", "tails"), simplify = FALSE)
# [[1]]
# flip..1. flip..2. flip..3. flip..4. flip..5. flip..6. flip..7. flip..8. flip..9. flip..10.
# heads tails heads tails heads tails heads heads tails heads
# Levels: heads tails
# [[2]]
# flip..1. flip..2. flip..3. flip..4. flip..5. flip..6. flip..7. flip..8. flip..9. flip..10.
# heads heads tails tails tails heads heads tails tails heads
# Levels: heads tails
This works in R before 4.1:
lapply(asplit(df, 1), factor, levels = c("heads", "tails"))
# [[1]]
# flip..1. flip..2. flip..3. flip..4. flip..5. flip..6. flip..7. flip..8. flip..9. flip..10.
# heads tails heads tails heads tails heads heads tails heads
# Levels: heads tails
# [[2]]
# flip..1. flip..2. flip..3. flip..4. flip..5. flip..6. flip..7. flip..8. flip..9. flip..10.
# heads heads tails tails tails heads heads tails tails heads
# Levels: heads tails