gpt4 book ai didi

r - 如何制作根据条件跨列多次连接的 R 循环

转载 作者:行者123 更新时间:2023-12-05 08:28:54 24 4
gpt4 key购买 nike

我有一个类似于以下的数据框:

    df <- data.frame(name = c("john", "sara", "bill"),
join_0_year = c(1990,1991,1992),
join_0_month = c(1,2,3),
join_0_day = c(20,21,22),
join_0_team = c("tigers", "lions", "bears"),
join_1_year = c(2000, 2001, 2002),
join_1_month = c(8,9,10),
join_1_day = c(14,15,16),
join_1_team = c("pirates", "colts", "panthers"))
df

name join_0_year join_0_month join_0_day join_0_team join_1_year join_1_month join_1_day join_1_team
1 john 1990 1 20 tigers 2000 8 14 pirates
2 sara 1991 2 21 lions 2001 9 15 colts
3 bill 1992 3 22 bears 2002 10 16 panthers

我的目标是将日期列连接成一个列。我的 df 有数百列(“join_0”到“join_400”),因此按名称手动调用列是不可能的。我想我需要制作某种 for-loop,我为此苦苦挣扎。我想要的结果是:

  name join_0_date join_0_team join_1_date join_1_team
1 john 1990-1-20 tigers 2000-8-14 pirates
2 sara 1991-2-21 lions 2001-9-15 colts
3 bill 1992-3-22 bears 2002-10-16 panthers

非常感谢任何帮助。

最佳答案

这行得通,但比其他答案差得多。刚发现这个任务很有趣。

library(tidyverse) 

df %>% {lapply(seq(sum(str_detect(string = names(df), pattern = "day"))),
function(y) y %>% {mutate(df, y=apply(df[(2+((.-1)*4)):(.*4)], 1, paste0, collapse = '-'))})} %>%
lapply(function(x) cbind(x$y)) %>%
cbind(df, .) %>%
dplyr::select(-which(str_detect(string = names(.), pattern = "year|month|day"))) %>%
setNames(ifelse(str_detect(names(.), pattern = "join_|name"), names(.),
paste0("join_", seq(str_detect(names(.), pattern = "join_"))-length(.)+1, "_date")))

name join_0_team join_1_team join_0_date join_1_date
1 john tigers pirates 1990-1-20 2000-8-14
2 sara lions colts 1991-2-21 2001-9-15
3 bill bears panthers 1992-3-22 2002-10-16

关于r - 如何制作根据条件跨列多次连接的 R 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73564500/

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