将列转置为 R 数据框中的行
Transpose columns to rows in R dataframe
在 R 中转换数据帧对我来说一直是个挑战。如何更改我的数据框:
df <- data.frame(level1 = c("A", "B","C"), cheese1.kg = c("58","63","33"), cheese2.kg = c("11","22","20"), column.other = c("yes","yes","yes"))
收件人:
desired.output <- data.frame(level1 = c("A","A","B","B","C","C"),
product = c("cheese1","cheese2","cheese1","cheese2","cheese1","cheese2"),
kg = c("58","11","63","22","33","20"),
column.other= c("yes","yes","yes","yes","yes","yes"))
?
我们可以用pivot_longer
library(tidyr)
pivot_longer(df, cols = starts_with('cheese'),
names_to = c("product", ".value"), names_sep = "\.",
values_transform = list(kg = as.integer))
-输出
# A tibble: 6 × 4
level1 column.other product kg
<chr> <chr> <chr> <int>
1 A yes cheese1 58
2 A yes cheese2 11
3 B yes cheese1 63
4 B yes cheese2 22
5 C yes cheese1 33
6 C yes cheese2 20
在 R 中转换数据帧对我来说一直是个挑战。如何更改我的数据框:
df <- data.frame(level1 = c("A", "B","C"), cheese1.kg = c("58","63","33"), cheese2.kg = c("11","22","20"), column.other = c("yes","yes","yes"))
收件人:
desired.output <- data.frame(level1 = c("A","A","B","B","C","C"),
product = c("cheese1","cheese2","cheese1","cheese2","cheese1","cheese2"),
kg = c("58","11","63","22","33","20"),
column.other= c("yes","yes","yes","yes","yes","yes"))
?
我们可以用pivot_longer
library(tidyr)
pivot_longer(df, cols = starts_with('cheese'),
names_to = c("product", ".value"), names_sep = "\.",
values_transform = list(kg = as.integer))
-输出
# A tibble: 6 × 4
level1 column.other product kg
<chr> <chr> <chr> <int>
1 A yes cheese1 58
2 A yes cheese2 11
3 B yes cheese1 63
4 B yes cheese2 22
5 C yes cheese1 33
6 C yes cheese2 20