如何使用R中的占位符引用具有公共前缀的多个变量 [英] How to refer to multiple variables with a common prefix using a placeholder in R

查看:701
本文介绍了如何使用R中的占位符引用具有公共前缀的多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个data.frame:

Suppose I have a data.frame:

x.a <- c(1,2,3,4,5)
y.b <- c(2,3,4,5,6)
y.c <- c(5,1,0,9,2)
y.d <- c(5,6,7,3,1)
x.e <- c(2,6,1,2,3)

df <- data.frame(x.a,y.b,y.c,y.d,x.e)

假设我要对变量yb,yc,yd进行排序: / p>

Suppose I want to rank the variables y.b, y.c, y.d:

df[2:4] <- sapply(df[2:4], function(x) rank(x))

有没有办法将一个函数应用于前缀 y的所有变量。?例如:

Is there a way to apply a function to all variables with the prefix y.? E.g.:

df[y.*] <- sapply(df[y.*], function(x) rank(x))


推荐答案

使用 grep 和正则表达式,如下所示:

With grep and regular expression, like this :

df <- data.frame(x.a,y.b,y.c,y.d,x.e)
df[, grep("y\\..", names(df))]
  y.b y.c y.d
1   2   5   5
2   3   1   6
3   4   0   7
4   5   9   3
5   6   2   1

您必须转义变量名称中的,第二个用于匹配一切。

You have to escape the . in the variable name, the second . is for matching everything.

这篇关于如何使用R中的占位符引用具有公共前缀的多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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