首页 > 解决方案 > How to subset rows with strings

问题描述

I want to use function for repetitively making up set with different names.

for example, if I have 5 random vectors.

number1<-sample(1:10, 3)
number2<-sample(1:10, 3)
number3<-sample(1:10, 3)
number4<-sample(1:10, 3)
number5<-sample(1:10, 3)

Then, I will use these vectors for selecting rows in raw data set(i.e. dataframe)

testset1<-raw[number1,]
testset2<-raw[number2,]
testset3<-raw[number3,]
tsetset4<-raw[number4,]
testset5<-raw[number5,]

It takes lot of spaces in manuscript for writing up each commands. I'm trying to shorten these commands with using 'function'

However, I found that it is hard to use variables in a function statement for writing 'text argument'. For example, it is easy to use variables like this.

mean_function<-function(x){
mean(x)
}

But, I want to use function like this.

testset "number with 1-5" <-raw[number"number 1-5",]

I would really appreciate your help.

标签: rfunction

解决方案


You don't need to create a function for this task, simply use lapply to loop over the list of elements produced by mget(), then set some names and finally put all results in the global environment:

rowSelected <-lapply(mget(paste0("number", 1:5)), function(x) raw[x, ])
names(rowSelected) <- paste0("testset", 1:5)
list2env(rowSelected, envir = .GlobalEnv)

推荐阅读