首页 > 解决方案 > 用括号括住以 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结尾的变量,并在它们周围加上括号?

谢谢你。

标签: r

解决方案


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

推荐阅读