gpt4 book ai didi

r - 如何使用 R 将列合并为单列

转载 作者:行者123 更新时间:2023-12-01 23:08:06 24 4
gpt4 key购买 nike

如何将这两列转换为一列

    structure(list(a = c("Q1-2020", "Q1-2020", "Q1-2020", "Q2-2020", 
"Q2-2020", "Q2-2020", "Q3-2020", "Q3-2020", "Q3-2020", "Q4-2021",
"Q4-2021", "Q4-2021"), b = c("Apr-2020", "May-2020", "Jun-2020",
"Jul-2020", "Aug-2020", "Sep-2020", "Oct-2020", "Nov-2020", "Dec-2020",
"Jan-2021", "Feb-2021", "Mar-2021")), row.names = c(1L, 21L,
41L, 61L, 81L, 101L, 121L, 141L, 161L, 181L, 201L, 221L), class = "data.frame")

预期输出

output = c("q1-2020", 
"Apr-20", "May-20", "Jun-20", "q2-2020", "Jul-20", "Aug-20",
"Sep-20", "q3-2020", "Oct-20", "Nov-20", "Dec-20", "q4-2021",
"Jan-21", "Feb-21", "Mar-21")

最佳答案

lapply 覆盖unique “a”

unlist(lapply(unique(dat$a), \(x) c(x, dat[dat$a == x, 'b'])))
# [1] "Q1-2020" "Apr-2020" "May-2020" "Jun-2020" "Q2-2020" "Jul-2020"
# [7] "Aug-2020" "Sep-2020" "Q3-2020" "Oct-2020" "Nov-2020" "Dec-2020"
# [13] "Q4-2021" "Jan-2021" "Feb-2021" "Mar-2021"

关于r - 如何使用 R 将列合并为单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70452684/

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