0

i have a big list of attributes and i want to convert them into a table.

I looks like this:

name  Key  Value
1     age   20
1     sex   1
2     age   20
2     sex   0
3     age   22
4     age   30
5     age   29
6     age   6

I want to convert it to something like this:

name  age  sex
1     20    1
2     20    0
3     22
4     30
5     29
6     6

Anyone have an idea?

#

EDIT My original list have a lot more values, not just 2. all the answers i saw don't answer my question. I'll try to explain it better with smaller table.

my table:

name  key    value
1     first   0
2     first   1
2     sec     1
1     sec     2
1     tr      1
2     tr      0
3     first   0
3     sec     0
4     first   0    

wanted result:

name first sec tr
1      0    2   1
2      1    1   0
3      0    0
4      0
  • 1
    Have a look at `tidyr::spread` – Andrew Gustar Jun 02 '19 at 13:56
  • Just a side note. [**Attribute**](http://adv-r.had.co.nz/Data-structures.html) can be taken as a "special word" in R. Therefore, it is best used sparingly(in my opinion). – NelsonGon Jun 02 '19 at 13:59
  • `tidyr::spread(df, key, value)` Or `tidyr::spread(df, key, value, fill = 0)` Or `tidyr::spread(df, key, value, fill = "")` depending how you want to `fill` the empty values. – Ronak Shah Jun 02 '19 at 15:26

1 Answers1

0

Here is an example using data from the OP with tidyr::spread().

rawData <- "name,Key,Value
1,age,20
1,sex,1
2,age,20
2,sex,0
3,age,22
4,age,30
5,age,29
6,age,6"

df <- read.csv(text=rawData,header=TRUE,stringsAsFactors=FALSE)

library(tidyr)

df %>% spread(.,key=Key,value=Value)

...and the output:

> df %>% spread(.,key=Key,value=Value)
  name age sex
1    1  20   1
2    2  20   0
3    3  22  NA
4    4  30  NA
5    5  29  NA
6    6   6  NA
> 

For additional background on spread() and its complement, gather(), please see R for Data Science, Chapter 12: Tidy Data.

Len Greski
  • 10,505
  • 2
  • 22
  • 33