-2

Is there a way I can get newdf from olddf, by creating a new variable for the column name and a variable for the result? Thank you.

olddf <- data.frame('A' = c('Z1','Z2','Z3'), 
                    'B' = c(100, 200, 500),
                    'C' = c(90, 50, 60),
                    'D' = c(NA, 50, NA))

newdf <- data.frame('A' = c('Z1','Z2','Z3','Z1','Z2','Z3'), 
                    'B' = c(100, 200, 500, 100, 200, 500),
                    'var' = c('C', 'C', 'C', 'D', 'D', 'D'),
                    'res' = c(90, 50, 60, NA, 50, NA))

2 Answers2

2
library(reshape2)
melt(olddf, id.vars = c('A','B'), value.name = 'res')
runr
  • 1,142
  • 1
  • 9
  • 25
1

You could also do pivot_longer from tidyr:

library(tidyverse)
pivot_longer(olddf, cols = c(C,D), names_to = "var", values_to = "res") %>%
  arrange(var)

Results:

# A tibble: 6 x 4
  A         B var     res
  <chr> <dbl> <chr> <dbl>
1 Z1      100 C        90
2 Z2      200 C        50
3 Z3      500 C        60
4 Z1      100 D        NA
5 Z2      200 D        50
6 Z3      500 D        NA
danh
  • 618
  • 3
  • 7