gpt4 book ai didi

重新排序列 : split the second half of columns up so that they come as every second

转载 作者:行者123 更新时间:2023-12-05 09:26:42 34 4
gpt4 key购买 nike

我想重新排列一个数据框,以便 1) 第一列始终保持在最前面,并且 2) 其余列的后半部分被拆分为每秒出现。

注意下面的例子

请查看示例数据:

# Example data
N <- "AB"
l_x_1 <- 1
l_x_2 <- 2
l_x_3 <- 3
# ... not it should be able to handle different number of columns

s_x_1 <- 1
s_x_2 <- 2
s_x_3 <- 3
# ... not it should be able to handle different number of columns (although always equal N of s_ and l_.

# Current state
df <- tibble(N, l_x_1, l_x_2, l_x_3, s_x_1, s_x_2, s_x_3)
df


# What I want (but potential to handle different number of As and Bs)
df <- tibble(N, l_x_1, s_x_1, l_x_2, s_x_2, l_x_3, s_x_3)
df


最佳答案

df[c(1, matrix(seq_along(df)[-1], 2, byrow = TRUE))]

# # A tibble: 1 × 7
# N l_x_1 s_x_1 l_x_2 s_x_2 l_x_3 s_x_3
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 AB 1 1 2 2 3 3

想法是使用matrix() 重新排序列索引。例如

c(matrix(1:6, 2, byrow = TRUE))
# [1] 1 4 2 5 3 6

关于重新排序列 : split the second half of columns up so that they come as every second,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73487872/

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