gpt4 book ai didi

r - 在R中按组将一列中的元素转置为多列

转载 作者:行者123 更新时间:2023-12-01 23:33:34 25 4
gpt4 key购买 nike

给定数据

test_id <- c(1, 1, 1, 2, 2, 2)
test_values <- c(1, 2, 3, 4, 5, 6)
test_df <- data.frame(test_id, test_values)
test_df

test_id test_values
1 1
1 2
1 3
2 4
2 5
2 6

我想将值列转置成一行

test_df$x1 <- c(1, 1, 1, 4, 4, 4)
test_df$x2 <- c(2, 2, 2, 5, 5, 5)
test_df$x3 <- c(3, 3, 3, 6, 6, 6)
test_df

test_id test_values x1 x2 x3
1 1 1 2 3
1 2 1 2 3
1 3 1 2 3
2 4 4 5 6
2 5 4 5 6
2 6 4 5 6

我最初的想法是这样的

test_df <- test_df %>%
group_by(test_id) %>%
mutate(X = t(test_values))%>%
ungroup()

但这不允许将列拆分为多个条目 - x1、x2、x3。非常感谢任何有关如何解决该问题的建议!

最佳答案

你可以用枢轴和连接来做到这一点:

test_id <- c(1, 1, 1, 2, 2, 2)
test_values <- c(1, 2, 3, 4, 5, 6)
test_df <- data.frame(test_id, test_values)

test_df %>%
group_by(test_id) %>%
mutate(var = seq_along(test_values)) %>%
pivot_wider(values_from="test_values", names_from="var", names_prefix="x") %>%
left_join(test_df %>% dplyr::select(test_id, test_values), .)
# Joining, by = "test_id"
# test_id test_values x1 x2 x3
# 1 1 1 1 2 3
# 2 1 2 1 2 3
# 3 1 3 1 2 3
# 4 2 4 4 5 6
# 5 2 5 4 5 6
# 6 2 6 4 5 6

或者,如果您只希望每个 test_id 一行,您可以只删除最后一行:

test_df %>% 
group_by(test_id) %>%
mutate(var = seq_along(test_values)) %>%
pivot_wider(values_from="test_values", names_from="var", names_prefix="x")
# # A tibble: 2 x 4
# # Groups: test_id [2]
# test_id x1 x2 x3
# <dbl> <dbl> <dbl> <dbl>
# 1 1 1 2 3
# 2 2 4 5 6

关于r - 在R中按组将一列中的元素转置为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65923889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com