0

my data set look like this

name  attribute  value
Tom    age        20
Tom    height     80
Tom    weight     100
Jack   age        22
Jack   height     90
Jack   weight     110 

and I want to get a data set like this

       Tom   Jack
age     20    22
height  80    90
weight  100   110

should be pretty stragiht forward in SAS by transpose of two variables but it is not so in R , how can I do it ? I tried melt and transpose , but failed ....

df1 <- read.table(header = TRUE, stringsAsFactors = FALSE,
           text = "name  attribute  value
Tom    age        20
           Tom    height     80
           Tom    weight     100
           Jack   age        22
           Jack   height     90
           Jack   weight     110 ")
rawr
  • 20,481
  • 4
  • 44
  • 78
cyanide
  • 11
  • 4

2 Answers2

2

We can use xtabs from base R

xtabs(value~attribute + name, df1)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

If you're starting R, I suggest you read Hadley Wickham and Garret Grolemund's new book R for Data Science. In it, they introduce the tidyverse which may make certain operations easier. You can certainly use xtabs - and it's a fantastic tool, especially for constructing sparse matrices - but it can be a little esoteric if you're new.

For instance, with your dataset in a data.frame, you can use tidyr to reshape. Note that I also use readr::read_table, which avoids the stringsToFactors issue.

library(tidyverse)

df1 <- read_table(
"name  attribute  value
Tom    age        20
Tom    height     80
Tom    weight     100
Jack   age        22
Jack   height     90
Jack   weight     110 ")

df1 %>%
    spread(name, value)

  attribute  Jack   Tom
*     <chr> <int> <int>
1       age    22    20
2    height    90    80
3    weight   110   100
Michael Griffiths
  • 1,399
  • 7
  • 14