r - 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.
解决方案
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)
推荐阅读
- c++ - 在不停止循环的情况下监视按键的最佳方法
- python - 使用子进程调用 NotePad++ 后,Python 不会开始执行其他代码,直到我关闭记事本程序
- redirect - 如何修复 Google Search Console 上的“重定向错误”
- c - 将小块数据写入闪存页面
- docker - Calico for policy 和 flannel 在 kubeadm (k8s -v1.22.3) 中不起作用,calico-kube-controllers 未准备好 (CrashLoopBackOff)
- java - 使用地图列表创建合并地图
- php - 如何在 Laravel Nova 中使用电子邮件发送文件?
- git-alias - 参数不工作的 git log 别名
- linked-list - 从链表中删除元素
- javascript - 我该如何解决这个问题?TypeError:无法在 react.js 中读取未定义的属性(读取“地图”)