0

My data set has different ~300 SMA’s and each of them tested 3 times. My sample data looks like this:

structure (list(SMA = c("SMA003-002", "SMA003-002", "SMA003-002",  "SMA105-002", "SMA105-002", "SMA105-002"), avg_inhi = c(10.983, 22.669, 41.821, 3.904, 1.032, 10.705)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

I hope get like this:

SMA avg-inhi_1  avg-inhi_2  avg-inhi_3
SMA003-002  10.983  22.669  41.821
SMA105-002  3.904   1.032   10.705
SMA107-002  11.297  -0.675  100.6
SMA108-002  98.436  100.193 101.204
SMA109-002  101.48  102.262 99.998
SMA110-002  99.478  100.056 99.057

I tried to use the following code:

 df <- data.frame(ag10)
ag10 %>%
    group_by(SMA) %>%
    pivot_wider(names_from = SMA, values_from = avg_inhi)

divibisan
  • 11,659
  • 11
  • 40
  • 58

2 Answers2

1

Should work with the addition of a line to track which instance within the SMA you're on:

library(dplyr); library(tidyr)

structure(list(SMA = c("SMA003-002", "SMA003-002", "SMA003-002",  "SMA105-002", "SMA105-002", "SMA105-002"), 
           avg_inhi = c(10.983, 22.669, 41.821, 3.904, 1.032, 10.705)), 
           row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame")) %>%

  group_by(SMA) %>%
  mutate(heading = paste0("avg-inhi_", row_number())) %>%
  pivot_wider(names_from = heading, values_from = avg_inhi)
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
1

You can use the spread function from tidyr package:

# Load Packages
library(dplyr)
library(tidyr)
library(glue)

# The dataset
data = structure (list(SMA = c("SMA003-002", "SMA003-002", "SMA003-002",  "SMA105-002", "SMA105-002", "SMA105-002"), 
                       avg_inhi = c(10.983, 22.669, 41.821, 3.904, 1.032, 10.705)), 
                  row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))


# Create sample numbers
id = rep(glue("avg_inhi_{1:3}"), 2)

# Reshaping
data %>%
  mutate(ID = id) %>%
  spread(key = ID, value = avg_inhi)
Mohammad
  • 21
  • 3