简体   繁体   English

从r的数据帧中制作大小为n / 2和2列的列表

[英]making list of size n/2 and 2 columns from a dataframe in r

Here is data: 这是数据:

myd <- data.frame (var1.1 = rnorm (10, 5,2), var1.2 = rnorm (10, 3,1),
                   varA.1 = rnorm (10, 5,2), varA.2 = rnorm (10,1,2), 
                    C.1 = rnorm (10, 3,1), C.2 = rnorm (10, 4,1))

I want create a list with of size 3 (n/2, if n is number of variable in dataframe) (with two columns each) 我想创建一个大小为3(n / 2,如果n是数据帧中变量的数量)的列表(每列两列)

mylist <- as.list (myd)

creats a list with each variable as component. 创建一个将每个变量作为组件的列表。 But I want create list of pair of variable in one unit - var1.1 and var1.2, similarly varA.1 and varA.2 or C.1 and C.2. 但是我想在一个单元中创建一对变量对列表-var1.1和var1.2,类似地是varA.1和varA.2或C.1和C.2。 Thus new list unit has 2 columns each. 因此,新列表单元每个都有2列。 Any solution ? 有什么办法吗?

I think this will give you what you want: 我认为这会给您您想要的:

lapply(seq(2, ncol(myd), by = 2), function(i) myd[, (i-1):i])

Now lets say you wanted to name each element in the list by the shared variable names of the data frame: 现在,假设您想使用数据框的共享变量名称来命名列表中的每个元素:

X <- lapply(seq(2, ncol(myd), by = 2), function(i) myd[, (i-1):i])
names(X) <- sapply(X, function(x){
    strsplit(names(x)[1], '\\.')[[c(1, 1)]]
})
X

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM