R中的左移列 [英] Left shift columns in R
本文介绍了R中的左移列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数据集
I have a data set like this
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
我将列左移,如果值左侧为空
I am shifting columns left, if the value on left is empty
推荐答案
以下是使用 data.table
的选项。按行顺序分组,不列出
data.table的子集( .SD
), un ==''
)> order ,转换为 list
然后在删除 grp列之后,使用原始列名称设置名称。
Here is an option using data.table
. Grouped by the sequence of rows, unlist
the Subset of data.table (.SD
), order
by the logical vector (un==''
), convert to list
and then set the names with the original column names after removing the 'grp' column
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
或者另一个选择是在创建序列列后将融化
到长格式,然后 dcast
转换为宽格式
Or another option is to melt
into long format after creating a sequence column, then dcast
it to wide format
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中的左移列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文