gpt4 book ai didi

r - 将每隔一行添加到新列

转载 作者:行者123 更新时间:2023-12-02 18:53:22 25 4
gpt4 key购买 nike

我正在寻找一种简单的方法来将每隔一行添加到 R 中的一个新列。我有 NCAA 篮球队在单独的连续行中互相比赛。下面的示例:圣乔斯正在玩拉萨尔,康涅狄格州正在玩西顿霍尔等。我希望每个“游戏”都在同一条线上。我已经弄乱了超前/滞后来解决这个问题,但这让我在第一行或最后一行出现错误,具体取决于我使用的是哪一行。这是我的数据示例:

# current data

Team spread price
St. Joes -3 -105
La Salle 3 -115
Connecticut -1.5 -105
Seton Hall 1.5 -115
Minnesota 5.5 -110
Penn State -5.5 -110


# desired output below

Team1 spread1 price1 Team2 spread2 price2
St. Joes -3 -105 La Salle 3 -115
Connecticut -1.5 -105 Seton Hall 1.5 -115
Minnesota 5.5 -110 Penn State -5.5 -110

最佳答案

使用 data.table 中的 dcast

library(data.table)
dcast(setDT(df)[, grp := gl(.N, 2, .N)], grp ~ rowid(grp),
value.var = setdiff(names(df), 'grp'))[, grp := NULL][]
# Team_1 Team_2 spread_1 spread_2 price_1 price_2
#1: St.Joes LaSalle -3.0 3.0 -105 -115
#2: Connecticut SetonHall -1.5 1.5 -105 -115
#3: Minnesota PennState 5.5 -5.5 -110 -110

数据

df <- structure(list(Team = c("St.Joes", "LaSalle", "Connecticut", 
"SetonHall", "Minnesota", "PennState"), spread = c(-3, 3, -1.5,
1.5, 5.5, -5.5), price = c(-105L, -115L, -105L, -115L, -110L,
-110L)), class = "data.frame", row.names = c(NA, -6L))

关于r - 将每隔一行添加到新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66468441/

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