Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Going from a dataframe with a factor column and numeric column to a dataframe with factor levels as columns and corresponding numeric values as rows

If I take the following two-column dataframe, with one column being a factor and the other being a numeric vector:

data <- data.frame(x=c("a","b","c","d","e","f","g","h"), y = c(1,2,3,3,2,1,5,6))
data$x <- as.factor(data$x)

How can I turn it into a new dataframe data2 where the factor levels of data$x are columns and the rows contain the corresponding numeric values from data$y, like so?

structure(list(a = 1, b = 2, c = 3, d = 3, e = 2, f = 1, g = 5, 
    h = 6), class = "data.frame", row.names = c(NA, -1L))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With base R, use rbind.data.frame:

d <- rbind.data.frame(data$y)
colnames(d) <- data$x

  a b c d e f g h
1 1 2 3 3 2 1 5 6

With pivot_wider:

tidyr::pivot_wider(data, names_from = x, values_from = y)

      a     b     c     d     e     f     g     h
1     1     2     3     3     2     1     5     6

or with xtabs:

xtabs(y ~ ., data = data) |> 
    as.data.frame.list()

  a b c d e f g h
1 1 2 3 3 2 1 5 6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading