Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (5.3k points)

I'm having trouble rearranging the following data frame:

set.seed(45)

dat1 <- data.frame(

    name = rep(c("firstName", "secondName"), each=4),

    numbers = rep(1:4, 2),

    value = rnorm(8)

    )

dat1

       name  numbers      value

1  firstName       1  0.3407997

2  firstName       2 -0.7033403

3  firstName       3 -0.3795377

4  firstName       4 -0.7460474

5 secondName       1 -0.8981073

6 secondName       2 -0.3347941

7 secondName       3 -0.5013782

8 secondName       4 -0.1745357

I want to reshape it so that each unique "name" variable is a rowname, with the "values" as observations along that row and the "numbers" as colnames. Sort of like this:

     name          1          2          3         4

1  firstName  0.3407997 -0.7033403 -0.3795377 -0.7460474

5 secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357

I've looked at melt and cast and a few other things, but none seem to do the job.

1 Answer

0 votes
by

You can use the reshape function from the base package that reshapes a data frame between ‘wide’ format with repeated measurements in separate columns of the same record and ‘long’ format with the repeated measurements in separate records.

In your case:

set.seed(45)

dat1 <- data.frame(

    name = rep(c("firstName", "secondName"), each=4),

    numbers = rep(1:4, 2),

    value = rnorm(8)

    )

    

reshape(dat1, idvar = "name", timevar = "numbers", direction = "wide")

Where:

Idvar-  the names of one or more variables in long format that identify multiple records

timevar - the variable in long format that differentiates multiple records

direction - either “wide” or “long”




 

Output:

     name    value.1   value.2 value.3    value.4

1  firstName  0.3407997 -0.7033403 -0.3795377 -0.7460474

5 secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...