是否有一种方法可以从olddf
中获得newdf
,通过为列名创建一个新变量和为结果创建一个变量?谢谢你。
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))
library(reshape2)
melt(olddf, id.vars = c('A','B'), value.name = 'res')
您也可以从tidyr
中获取pivot_longer
:
library(tidyverse)
pivot_longer(olddf, cols = c(C,D), names_to = "var", values_to = "res") %>%
arrange(var)
结果:
# 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