如何通过基于行值创建新变量来重塑数据框以进行分析
How to reshape a dataframe for analysis by creating new variables based on row values
有没有一种方法可以通过为列名创建一个新变量并为结果创建一个变量来从 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
有没有一种方法可以通过为列名创建一个新变量并为结果创建一个变量来从 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