PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 1, 2022

[FIXED] How to transform a data frame by using pivot_longer

 November 01, 2022     dataframe, pivot, r, tidyr     No comments   

Issue

I have the following data set

df <- data.table(
  id = c(1),
  field_a.x = c(10),
  field_a.y = c(20),
  field_b.x = c(30),
  field_b.y = c(40))

And, I'd like to transform it into

df_result <- data.table(
  id = c(1),
  field_name = c("field_a", "field_b"),
  x = c(10, 30),
  y = c(20, 40))

by using "pivot_longer" function taking into account postfixes ".x" and ".y".

It will be much more fields in my real data. But I would like to see how to process it for 2 for example.

Thanks!


Solution

You could set ".value" in names_to and supply one of names_sep or names_pattern to specify how the column names should be split.

library(tidyr)

df %>%
  pivot_longer(-1, names_to = c("field_name", ".value"), names_sep = "\\.")

# # A tibble: 2 × 4
#      id field_name     x     y
#   <dbl> <chr>      <dbl> <dbl>
# 1     1 field_a       10    20
# 2     1 field_b       30    40

names_sep = "\\." can be replaced with names_pattern = "(.+)\\.(.+)".



Answered By - Darren Tsai
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing