'Pivotlonger with identical Column names

my data looks like

Nr. Type 1 Type 2 Type 1 Type 2
1     400    600    100   800
2     500    400    900   300
3     200    200    400   700
4     300    600    800   300

and I want to create Boxolplots of Type 1 and type 2. Pivotlonger makes Type 1 and Type 1.1 which is not what I Need.

Maybe someone can help me.

r


Solution 1:[1]

It turns out your issue was not with the pivot_longer() but with the subsetting of your original data.frame using [. There is no direct control over the requirement that the output of [ or base::subset() have unique column names so you need do something else to subset your data and avoid losing column names. This is discussed in this question so borrowing from one of the answers, you can use:

library(tidyverse)

# data with extra column to be removed
d <- structure(list(Nr. = 1:4, `Type 1` = c(400L, 500L, 200L, 300L), x = 1:4, `Type 2` = c(600L, 
400L, 200L, 600L), `Type 1` = c(100L, 900L, 400L, 800L), `Type 2` = c(800L, 
300L, 700L, 300L)), row.names = c(NA, -4L), class = "data.frame")

# remove extra column without changing names then pivot
data.frame(as.list(d)[-3], check.names = FALSE) %>% 
  pivot_longer(-Nr.) %>% 
  ggplot(aes(name, value)) +
  geom_boxplot()

Created on 2022-02-22 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1