gpt4 book ai didi

r - R中的左移列

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

我有一个这样的数据集

temp <- structure(list(col_1 = c("", "P9603", "", "", "11040", 
"80053"), col_2 = c("84484", "80061", "", "80061", "A0428", "85025"
), col_3 = c("V2632", "82310", "", "", "", "86357"), col_4 = c("J1170",
"84305", "62311", "80061", "", ""), col_5 = c("", "86708", "J0690",
"", "", "")), .Names = c("col_1", "col_2", "col_3", "col_4",
"col_5"), class = c("data.table", "data.frame"))

col_1 col_2 col_3 col_4 col_5
1: 84484 V2632 J1170
2: P9603 80061 82310 84305 86708
3: 62311 J0690
4: 80061 80061
5: 11040 A0428
6: 80053 85025 86357

是否有可能像这样移动列
   col_1 col_2 col_3 col_4 col_5
1: 84484 V2632 J1170 #LEFT SHIFT 1
2: P9603 80061 82310 84305 86708 #NO CHANGE
3: 62311 J0690 #LEFT SHIFT 3
4: 80061 80061 #LEFT SHIFT 1 FOR FIRST ITEM,
#LEFT SHIFT 2 FOR 2ND ITEM
5: 11040 A0428 #NO CHANGE
6: 80053 85025 86357 #NO CHANGE

如果左侧的值为空,我将向左移动列

最佳答案

这是一个使用 data.table 的选项.按行顺序分组,unlist data.table 的子集 ( .SD ), order通过逻辑向量( un=='' ),转换为 list然后在删除“grp”列后使用原始列名设置名称

setnames(temp[, {un <- unlist(.SD); as.list(un[order(un=='')])},
.(grp = 1:nrow(temp))][, grp := NULL], names(temp))[]
# col_1 col_2 col_3 col_4 col_5
#1: 84484 V2632 J1170
#2: P9603 80061 82310 84305 86708
#3: 62311 J0690
#4: 80061 80061
#5: 11040 A0428
#6: 80053 85025 86357

或者另一种选择是 melt创建序列列后转换为长格式,然后 dcast它是宽格式
dcast(melt(temp[, n := seq_len(.N)], id.var = 'n')[order(n, value == ''),
.(value, variable = names(temp)[1:5]), n], n ~ variable)[, n := NULL][]

关于r - R中的左移列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47484244/

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