-1

I have a data set below. I need to transform them so that variables names are now values

>(p2)
   B        D        F 
  36.0    38.93    36.06

I need to have like below

p2
Col1   COl2
 B      36.0
 D      38.93
 F      36.06
Rfer R
  • 69
  • 5

3 Answers3

0

You can use the gather function from the Tidyverse :

library(tidyverse)
gather(p2, key = "Col1", value = "Col2")
cyrilb38
  • 924
  • 6
  • 17
  • this is not working – Rfer R Aug 19 '19 at 08:51
  • Could you provide the error that you get ? – cyrilb38 Aug 19 '19 at 08:52
  • Error in UseMethod("gather_") : no applicable method for 'gather_' applied to an object of class "c('double', 'numeric')" – Rfer R Aug 19 '19 at 08:54
  • Oh i guess you have a named vector. Could you provide the output of `class(p2)`. Maybe you just need to convert it to dataframe (if you need to) : `data.frame(p2)`. Or you could transpose it if you need a matrix, as @Steve suggest – cyrilb38 Aug 19 '19 at 09:03
0
data.frame(Col1= names(p2), Col2 = p2, row.names = NULL) 

Data :

p2 <- c(B =36.0, D=38.93, F= 36.06)
Sang won kim
  • 524
  • 5
  • 21
0

If this is a vector:

p2 <- c(B = 36, D = 38.93, F = 36.06)

Then enframe from package tibble could help:

library(tibble)
enframe(p2)
# # A tibble: 3 x 2
# name  value
# <chr> <dbl>
# 1 B      36  
# 2 D      38.9
# 3 F      36.1

You could change names using

enframe(p2, "Col1", "Col2")
Marek
  • 49,472
  • 15
  • 99
  • 121