-1

Can you suggest a solution for this in tidyr?

I tried doing the same with the gather and spread functions, but with no result

# Input data
x = c("a","a","a","b","b","b")
y = c(5.1,5.8,5.3,2.2,2.7,2.4)
z = c("l","m","n","l","m","n")
xy = as.data.frame(cbind(x,y,z))

# output "Is Condition"
  x   y  z
1 a 5.1  l
2 a 5.8  m
3 a 5.3  n
4 b 2.2  l
5 b 2.7  m
6 b 2.4  n

# I need output like this 
    a   b  z
1 5.1 2.2  l
2 5.8 2.7  m
3 5.3 2.4  n

Sorry guys , i was not able to post the exact requirement. below is what is the requirement. Not able to make it exact reproducible ...

#Input
Sl No   TESTER  MP  A1  B1  C1
1   435 A   4.96    6.75    4
1   435 B   10.87   83.86   4.19
1   435 C   12.83   126.38  1.01
1   435 D   12.9    129.22  3.63
1   435 E   10.64   74.41   4.25
2   435 A   4.96    7.43    2.43
2   435 B   10.94   84.53   3.43
2   435 C   12.84   126.55  2.57
2   435 D   12.9    128.95  2.1
2   435 E   10.6    74.23   5.04



 #Output Required

Sl  Test A        B       C      D       E       A       B       C        D         E     A    B       C       D       E  
1   435 4.96    10.87   12.83   12.9    10.64   6.75    83.86   126.38  129.22  74.41   4.00    4.19    1.01    3.63    4.25
2   435 4.96    10.94   12.84   12.9    10.6    7.43    84.53   126.55  128.95  74.23   2.43    3.43    2.57    2.10    5.04
user3883642
  • 31
  • 1
  • 5
  • Welcome to SO. Please show us what you have exactly tried with spread. And [have a look at this cheatsheet here](https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf) - at the beginning it helped me a lot for those cases – tjebo Jul 30 '18 at 08:59
  • 1
    Can you post the code that did not work as expected? `spread` should work fine. – markus Jul 30 '18 at 09:20
  • 1
    It wont be possible to have multiple columns with same name as shown in your output. – rar Jul 30 '18 at 10:37
  • I saw through suggested similar Questions. In all examples shown there is only 1 value column (spread(key = ,value = )) where as here it is 3 columns (A1,B1,C1). Has any on tried this out confirming ? @rar column names not so important. Concern is can this be done ? I have have tried it with spread (key = MP , value = A1) does not seems to work. Request team to support. – user3883642 Jul 31 '18 at 08:37

1 Answers1

0
  • The key parameter contains the name of the column that contains the new column names
  • The value parameter contains the name of the column that contains the values to fill them with.

.

library(tidyr)
xy %>% spread(x,y) # or spread(xy, x, y)
#   z   a   b
# 1 l 5.1 2.2
# 2 m 5.8 2.7
# 3 n 5.3 2.4
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167