Turn a Row into a Column in R

Asked

Viewed 597 times

2

I have the following dataframe in R I need to turn the row into a column as follows:

   Nome  Valor 
1  x     1.1
2  x     2.2
3  y     3.3
4  y     4.4
5  z     5.5
6  z     6.6

And I need him to stay that way:

   x    y    z
1  1.1  3.3  5.5
2  2.2  4.4  6.6

Thank you!

  • 1

    How is this question out of scope?

  • 1

    Duplicate, but it is not out of scope.

  • 1

    @Carloseduardolagosta Not quite a duplicate, this question asks to transpose, this is closer.

  • 1

    That’s right, @Noisy. Anyway, I don’t see why it was considered out of scope.

1 answer

2

There are several ways to reformat data from long to wide format. I will use the package tidyverse.

library(tidyverse)

df1 %>%
  group_by(Nome) %>%
  mutate(Grp = row_number()) %>%
  pivot_wider(names_from = "Nome", values_from = "Valor") %>%
  select(-Grp)
## A tibble: 2 x 3
#      x     y     z
#  <dbl> <dbl> <dbl>
#1   1.1   3.3   5.5
#2   2.2   4.4   6.6

Dice.

df1 <- read.table(text = "
   Nome  Valor 
1  x     1.1
2  x     2.2
3  y     3.3
4  y     4.4
5  z     5.5
6  z     6.6
", header = TRUE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.