首页 > 解决方案 > 将具有相同后缀的多个变量的值重新编码为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 新手,正在尝试学习自动化我的代码。提前感谢您的帮助。

标签: 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 帮助页面中定义?regexgsub函数(和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 whilegrep only does it at the first such position. Bothgsub and? details are described in the same R help page which can be found atgrep`。


推荐阅读