I'm running into an issue I cannot explain: I have a data.frame of numeric columns and adding a new column in any way ($ operator, cbind ...) changes the type of all other columns to character
> ab_dt = data.frame(ab_mat)
> unique(apply(ab_dt, 2, class))
[1] "numeric"
> a = meta[rownames(ab_dt), "Location"]
> class(a)
[1] "factor"
> ab_dt$Location = a
> unique(apply(ab_dt, 2, class))
[1] "character"
Does anyone know why this is happening?
CodePudding user response:
It has something to do with how you calculate the class. I would suggest to use sapply
instead. Using a tibble
instead of a data.frame
allows you to always keep track of column classes in printing:
data <- data.frame(
a = factor("foo", levels = c("foo", "bar")),
b = "baz"
)
data
#> a b
#> 1 foo baz
unique(apply(data, 2, class))
#> [1] "character"
sapply(data, class)
#> a b
#> "factor" "character"
tibble::as_tibble(data)
#> # A tibble: 1 x 2
#> a b
#> <fct> <chr>
#> 1 foo baz
```