R 循环,创建新变量作为现有变量的函数

R 循环,创建新变量作为现有变量的函数,r,for-loop,grepl,R,For Loop,Grepl,我有一些数据,包含400多列和大约80个观察值。我想使用for循环遍历每一列,如果它包含所需的前缀exp\u,我想创建一个新的列,该列的值除以一个引用列,存储为相同的名称,但带有后缀\u pp。我还想用另一个前缀rev\uu做一个else if,但我认为只要我能解决第一个问题,其余的问题我可以自己解决。以下是一些示例数据: exp_alpha exp_bravo rev_charlie rev_delta pupils 10 28

我有一些数据,包含400多列和大约80个观察值。我想使用for循环遍历每一列,如果它包含所需的前缀
exp\u
,我想创建一个新的列,该列的值除以一个引用列,存储为相同的名称,但带有后缀
\u pp
。我还想用另一个前缀
rev\uu
做一个else if,但我认为只要我能解决第一个问题,其余的问题我可以自己解决。以下是一些示例数据:

exp_alpha     exp_bravo    rev_charlie     rev_delta     pupils
10            28           38              95            2
24            56           39              24            5
94            50           95              45            3
15            93           72              83            9
72            66           10              12            3
第一次尝试时,循环正常运行,但只存储if语句为true的最后一列,而不是存储if语句为true的每一列。我做了一些调整,丢失了代码,但现在有了这个运行没有错误,但根本不修改数据帧

for (i in colnames(test)) {
  if(grepl("exp_", colnames(test)[i])) {
    test[paste(i,"pp", sep="_")] <- test[i] / test$pupils)
  }
}
for(i在colnames(test)中){
if(grepl(“exp_389;”,colnames(test)[i])){

test[paste(i,“pp”,sep=“”)]几乎正确,您没有定义循环的长度,因此没有发生任何事情。请尝试以下操作:

for (i in 1:length(colnames(test))) {
  if(grepl("exp_", colnames(test)[i])) {
  test[paste(i,"pp", sep="_")] <- test[i] / test$pupils
  }
}
for(i in 1:length(colnames(test))){
if(grepl(“exp_389;”,colnames(test)[i])){

test[粘贴(i,“pp”,sep=“”)]作为@timfaber答案的替代,您可以保持第一行不变,但不能将
i
作为索引:

for (i in colnames(test)) {
  if(grepl("exp_", i)) {
    print(i)
    test[paste(i,"pp", sep="_")] <- test[i] / test$pupils
  }
}
for(i在colnames(test)中){
if(grepl(“exp_uu”,i)){
印刷品(一)

测试[粘贴(i,“pp”,sep=“”)]线性溶液:

不要为此使用循环!您可以线性化代码,并比在列上循环快得多。以下是如何做到这一点:

# Extract column names
cNames <- colnames(test)
# Find exp in column names
foo <- grep("exp", cNames)
# Divide by reference: ALL columns at the SAME time
bar <- test[, foo] / test$pupils
# Rename exp to pp : ALL columns at the SAME time
colnames(bar) <- gsub("exp", "pp", cNames[foo])
# Add to original dataset instead of iteratively appending 
cbind(test, bar)
#提取列名

cNames似乎有用,谢谢你的帮助!请注意:当我运行timfaber的建议时,新列名变成了带有适当附加“_pp”的数字(因为它是第I列,而我是一个数字)。不过修复很简单,在第三行中,我将“…粘贴(I),”替换为“…粘贴(colnames(test)[I],…“感谢你今天解决了我所有的问题@PoGibas