在数据框的每一行上选择不同的列数 [英] Selecting different numbers of columns on each row of a data frame
问题描述
这个问题是关于在数据帧的每一行上选择不同数量的列。我有一个数据框:
This question is about selecting a different number of columns on every row of a data frame. I have a data frame:
df = data.frame(
START=sample(1:2, 10, repace=T), END=sample(2:4, 10, replace=T),
X1=rnorm(10), X2=rnorm(10), X3=rnorm(10), X4=rnorm(10)
)
我希望有一种没有循环的方式来选择列(START [ i]:END [i])在数据框的所有行的第i行上加2。
I would like to have a way without loops to select columns (START[i]:END[i])+2 on row i for all rows of my data frame.
推荐答案
Base R解决方案
Base R solution
lapply(split(df,1:nrow(df)),function(row) row[(row$START+2):(row$END+2)])
或类似上述注释中的内容(我将输出存储在列表中)
Or something similar as given in the comment above (I would store the output in a list)
library(plyr)
alply(df,1,function(row) row[(row$START+2):(row$END+2)])
按OP的每个请求进行编辑:
Edit per request of OP:
要获取TRUE / FALSE索引矩阵,请使用以下R基本解决方案
To get a TRUE/FALSE index matrix, use the following R base solution
idx_matrix=col(df)>=df$START+2&col(df)<=df$END+2
df[idx_matrix]
但是请注意,此处您丢失了一些信息(与基于列表的解决方案相比) )。
Note, however, that you lose some information here (compared to the list based solution).
这篇关于在数据框的每一行上选择不同的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!