r - 用括号括住以 sd 结尾的变量
问题描述
我有一张大桌子,我想在每个以“_sd”结尾的变量周围加上括号。
这是一个例子:
a<- c(0,2,3,4,10,7,6,5,4,3)
b_sd<-c(0,2,3,4,8,6,5,4,3,1)
c<- c(0,2,3,4,10,7,6,5,4,3)
d_sd<-c(0,2,3,4,8,6,5,4,3,1)
dta <- data.frame(a=a, b_sd=b_sd, c=c, d_sd=d_sd)
dta
# this is the slow way:
dta[,2] <- paste0("(", dta[,2], ")")
dta[,4] <- paste0("(", dta[,4], ")")
# this is what I want:
dta
上面的代码可以工作,但是对于我拥有的所有变量来说它非常慢。我怎样才能自动化它?1.找到以_sd结尾的变量,并在它们周围加上括号?
谢谢你。
解决方案
If your dataset is large, try the data.table package for operations like these. Here is a vignette if you want to know more.
Here is the code utilizing the data.table package :
library(data.table)
##Set as data table
setDT(dta)
##Select the relevant variables
sd_names<-grep("_sd",names(dta),value = T)
dta[,(sd_names):=lapply(.SD,function(x) {paste0("(",x,")")}),.SDcols=sd_names]
###
dta
推荐阅读
- javascript - 如何传递带有参数的函数作为参数本身?
- python-3.x - 如何在Python中仅使用Selenium长按(按住)鼠标左键
- laravel - 从 AWS S3(非公共存储桶)下载 Laravel 中的文件
- java - 基于参数值的Jackson抽象类反序列化
- javascript - 如何在 agularjs 中进行 izitoast ng-repeat
- python - 关于KL Divergence的查询
- python - 如何修复嵌入不发送踢/禁止(discord.py)
- javascript - height() 返回一个低于实际高度的值
- javascript - 如何在 vue 列表中添加指向项目的外部链接?
- python - Python-Telegram-Bot - '与 api.telegram.org 的连接超时'