0

I have a dataframe with 2 columns: name and value:

name               value
received            63
received.tod        12
received.daybf      50
mantioned           workings
houses              located

I want to turn it into this:

received   received.tod     received.daybf    mantioned       houses
   63           12               50            workings      located

So as you see values from first column became columns, and values from second column became values in those columns accordingly. How could i do that?

french_fries
  • 1,149
  • 6
  • 22
  • You can use `library(tidyr)`, then `spread(df, name, value)`, or `pivot_wider(df)`, where `df` is your data frame. – neilfws Aug 20 '20 at 01:04
  • 1
    Note that your `value` column contains both string and integer values, so all the new columns will be of type character - you may want to convert the columns with integers to type numeric, depending on what you want to do with the data. – neilfws Aug 20 '20 at 01:12

3 Answers3

1

I would probably do something like this:

dat <- data.frame(name = c('a', 'b', 'c'),
                  value = c(63, 12, 'workings'))
as.data.frame(as.list(dat$value), col.names=dat$name)
#>    a  b        c
#> 1 63 12 workings
Vincent
  • 15,809
  • 7
  • 37
  • 39
1

using data.table:

DT <- data.table(name = c('received', 'received.tod', 'received.daybf', 'mantioned', 'houses'),
                 value = c('63', '12', '50', 'workings', 'located'))

dcast(DT, . ~ name, value.var = 'value')

Output:

   .  houses mantioned received received.daybf received.tod
1: . located  workings       63             50           12
daniellga
  • 1,142
  • 6
  • 16
1
df <- data.frame(name = c('received', 'received.tod', 'received.daybf', 'mantioned', 'houses'), value = c(63, 12, 50, 'workings', 'located'))

tmp <- data.frame(matrix(df$value, nrow = 1))
names(tmp) <- df$name
Haci Duru
  • 456
  • 3
  • 9