CodexBloom - Programming Q&A Platform

scenarios when trying to pivot longer data with multiple value columns in R using `tidyr`

👀 Views: 66 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
r tidyr data-wrangling R

I've looked through the documentation and I'm still confused about I'm collaborating on a project where I can't seem to get I'm stuck on something that should probably be simple. I'm working with an scenario when trying to reshape my data frame from wide to long format using `tidyr::pivot_longer()`. My dataset has several measurement columns for different variables, and I want to keep all of them in the long format for further analysis. However, I keep getting the following behavior: `behavior: need to convert data to a long format. Please check that your data is in a valid long format.` Here's a simplified version of my data frame: ```r library(tidyr) # Sample data frame my_data <- data.frame( ID = 1:3, height = c(5.5, 6.0, 5.8), weight = c(130, 150, 140), age = c(25, 30, 22) ) ``` I want to pivot this data to have a column for measurement type and another for values, like this: | ID | measurement | value | |----|-------------|-------| | 1 | height | 5.5 | | 1 | weight | 130 | | 1 | age | 25 | | 2 | height | 6.0 | | 2 | weight | 150 | | 2 | age | 30 | | 3 | height | 5.8 | | 3 | weight | 140 | | 3 | age | 22 | I tried the following code: ```r long_data <- my_data %>% pivot_longer(cols = c(height, weight, age), names_to = "measurement", values_to = "value") ``` But it throws an behavior instead of creating the long format data frame. I've ensured that the columns I want to pivot are correctly specified, and I'm using `tidyr` version 1.1.4. Could someone guide to understand why this is happening and how I can resolve it? The project is a service built with R. My development environment is macOS. I'd really appreciate any guidance on this. Thanks for taking the time to read this! I'm open to any suggestions.