矩阵列表中的列名列表

时间:2017-07-25 18:40:59

标签: r list matrix

我有一个包含6000列的矩阵,每列属于100个"组中的一个"我需要。我需要将此矩阵转换为列表100个较小的矩阵。这是我所拥有的玩具示例:

list(cbind(c(2,2,2),c(4,4,4)),cbind(c(3,3,3),c(1,1,1)))

所以"组"由每个colname的姓氏标识,这里有2组。我需要的结果如下:

lapply(do.call(cbind,sapply(something here to find the columns in each group)))

我一直在思考,我认为它应该是这样的:

public ActionResult ChangeDefaultUserLockingSetting(int PasswordAttempts, int DefaultLockingTime)
        {
            var defaultAccountSettings = new DefaultAccountSettingsDataContext();

            var accountSettings = defaultAccountSettings.DefaultAccountSettings.First(u => u.id == 1);

//The object should be modified and not his local value 
            accountSettings.DefaultAccountLockoutTimeSpan = DefaultLockingTime;
            accountSettings.MaxFailedAccessAttemptsBeforeLockout = PasswordAttempts;

            defaultAccountSettings.SubmitChanges();
            return View("Index", loadAdministrationViewModel());
        }

但我还没弄清楚到底是怎么做到的。

1 个答案:

答案 0 :(得分:0)

#Obtain the last part of each column names
groups = sapply(strsplit(x = colnames(mat), split = " "), function(x) x[2])

#Go through each unique column name and extract the corresponding columns
lapply(unique(groups), function(x) mat[,which(groups == x)])
#[[1]]
#     2018.3 1 2019.1 1
#[1,]        2        4
#[2,]        2        4
#[3,]        2        4

#[[2]]
#     2018.3 2 2019.2 2
#[1,]        3        1
#[2,]        3        1
#[3,]        3        1

OR

lapply(split(1:NCOL(mat), sapply(strsplit(x = colnames(mat), split = " "),
                                 function(x) x[2])), function(i) mat[,i])
#$`1`
#     2018.3 1 2019.1 1
#[1,]        2        4
#[2,]        2        4
#[3,]        2        4

#$`2`
#     2018.3 2 2019.2 2
#[1,]        3        1
#[2,]        3        1
#[3,]        3        1