Reputation: 463
I do have a dataframe with 55 columns called df.example
. Each columns of this df possess a title, let's say "A1","A2" to "A55"
I also have 16 elements within a list called Factor.lst
that regroup the 55 titles.
Now I would like to subset the df.example
using the encoded titles within the 16 elements called Factor. For exemple, I tried this way :
F1 <- subset(df.example, select=c(get(Factor.lst)))
Or
F1 <- subset(df.example, select=c(get(Factor.lst[1:16])))
Upvotes: 1
Views: 64
Reputation: 886938
Try
res <- lapply(mget(ls(pattern="^Factor\\d+")),
function(x) subset(df.example, select=x))
lapply(res, head,2)
#$Factor1
# A5 A8 A32
#1 2 5 18
#2 12 15 10
#$Factor2
# A1 A7 A52
#1 6 7 10
#2 5 5 9
#$Factor3
# A9 A13 A42
#1 10 10 20
#2 8 5 11
If you want to do the same with Factor.lst
Map(`[`, list(df.example), Factor.lst)
Factor1 <- paste0("A", c(5,8, 32))
Factor2 <- paste0("A", c(1, 7, 52))
Factor3 <- paste0("A", c(9, 13, 42))
Factor.lst <- list(Factor1, Factor2, Factor3)
set.seed(24)
df.example <- as.data.frame(matrix(sample(1:20, 55*5, replace=TRUE),
ncol=55, dimnames=list(NULL, paste0("A", 1:55))))
Upvotes: 1