r - 将具有相同后缀的多个变量的值重新编码为R中具有不同后缀的新变量
问题描述
library(Hmisc)
install.packages("expss")
col1.5pt <- c(1,2,4,5)
col2.5pt <- c(1,2,3,4)
col3 <- c(3,4,5,1)
col4.5pt <- c(2,3,2,4)
col5 <- c(3,NA,4,5)
df<- data.frame(col1.5pt,col2.5pt,col3,col4.5pt,col5)
abc <- c("col1.5pt", "col2.5pt", "col4.5pt")
cde <- c("col1.T2b", "col2.T2b", "col4.T2b")
df[cde]<-sapply(df[abc], function(x) recode(x,1:2~1,3~2,4:5~3))
我基本上必须将 .5pt 的变量重新编码为 .T2b。目前,我正在选择这些变量,但由于我有很多数据集,我必须在其中创建这些类型的变量。我想要一些可以用 .5pt 选择所有变量并将它们重新编码为 .T2b 的东西。我是 R 新手,正在尝试学习自动化我的代码。提前感谢您的帮助。
解决方案
如果我没看错,您想根据以“.5pt”结尾的现有列命名新列,然后将该函数应用于原始列以形成新值集。
abc <- grep("\\.5pt$", names(df), value=TRUE) #create source column names
# use double escape "\\." to match a period ; naked periods are regex wildcards
cde.new <- gsub("\\.5pt$", ".T2b", abc) # create destination names
# fortunately yoiu can use a vector of names on the LHS of `[.]<-`
df[cde.new] <- sapply(df[abc], function(x) recode(x,1:2~1,3~2,4:5~3))
df
#------------
col1.5pt col2.5pt col3 col4.5pt col5 col1.T2b col2.T2b col4.T2b
1 1 1 3 2 3 1 1 1
2 2 2 4 3 NA 1 1 2
3 4 3 5 2 4 3 2 1
4 5 4 1 4 5 3 3 3
该grep
函数使用广义正则表达式来处理字符值向量。在其默认模式下,它需要两个参数,第一个是定义匹配规则的模式,第二个是正在考虑的向量。它返回一个数字,该数字是向量中任何字符值的相对位置。当 时value=TRUE
,它改为返回实际的字符值而不是它们的位置。模式的匹配规则在 R 帮助页面中定义?regex
。gsub
函数(和gsub sub function) match a pattern (first argument) and then substitutes new characters for the matched ones (second argument) within the vector given in the third argument.
sub does this at all positions matched while
grep only does it at the first such position. Both
gsub and
? details are described in the same R help page which can be found at
grep`。
推荐阅读
- python - 在另一个函数中调用定义在一个函数中的变量并使用按钮重置变量
- kotlin - Kotlin 中这些东西的用途是什么?
- powershell - 如何在 Azure DevOps 中删除多个测试用例
- android - 检索并保存选定的微调器位置
- r - 从模型摘要中提取系数以制作方程
- c# - 如何检查 JObject 中的对象是否存在,如果不存在则添加新对象或将其添加到现有对象中?
- database - 外部数据库到 oracle 融合
- node.js - 无法在节点 v10.16.0 中安装节点雷吉
- jquery - 跟踪悬停的元素并在特定时间范围内忽略休息
- java - 如何将我的结果数据与来自 firebase 的所有数据进行比较