在R中创建一个循环,以将相同的函数应用于许多相似命名的变量 [英] Creating a loop in R to apply the same functions to many similarly named variables

查看:135
本文介绍了在R中创建一个循环,以将相同的函数应用于许多相似命名的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的数据集具有名称非常相似的变量.我必须一次将相同的函数应用于所有13个变量,而我试图缩短代码,而不是分别进行每个变量.

I am using a dataset with variables that have very similar names. I have to apply the same functions to all 13 variables at a time and I'm trying to shorten the code, instead of doing each variable individually.

q01a.F=factor(q01a)
q01b.F=factor(q01b)
q01c.F=factor(q01c)
q01d.F=factor(q01d)
q01e.F=factor(q01e)
q01f.F=factor(q01f)
q01g.F=factor(q01g)
q01h.F=factor(q01h)
q01i.F=factor(q01i)
q01j.F=factor(q01j)
q01k.F=factor(q01k)
q01l.F=factor(q01l)
q01m.F=factor(q01m)

建议?

推荐答案

## suppose dnow is the data.frame with your variables of interest
dnow <- data.frame(q01a=rep(1,10), q01b=rep(2,10), q01c=rep(3,10), q02=rlnorm(10))
## we need to extract the variable names we need
## (they start with q01 and end with a, b or c
## dnow is your data.frame
vnames <- grep("^q01[a-c]", names(dnow), value=TRUE) ## regular expression matching the names
for (i in vnames) {
    dnow[,paste(i, ".F", sep='')] <- factor(dnow[,i]) 
}

这篇关于在R中创建一个循环,以将相同的函数应用于许多相似命名的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆