【问题标题】:Can I add column names to a variable while I run a `for` loop in R?我可以在 R 中运行“for”循环时将列名添加到变量中吗?
【发布时间】:2021-11-24 00:34:33
【问题描述】:

我在 R 中做一个练习,要求我找到一些变量的茎叶图。例如,此过程的第一次迭代将是:

> with(data = Commercial_Properties, stem(x = Op_Expense_Tax))

  The decimal point is at the |

   2 | 0
   4 | 080003358
   6 | 012613
   8 | 00001223456001555689
  10 | 013344566677778123344666668
  12 | 00011115777889002
  14 | 6

在此之后,我将不得不为更多变量重复执行此操作。因此,在我的改进之路上,我记得我的一位精通编程的朋友提到,如果您重复执行相同的任务,则需要完成某种for 循环。

因此我尝试这样做:

for (i in 2:5){
  
  stem_colnames(Commercial_Properties[i]) = with(data = Commercial_Properties, stem(x = unlist(Commercial_Properties[,i])))
  
}

我想要代码做的是从我的数据框中提取列名,将其附加到 stem_ 以创建相应变量的名称,然后生成相应的茎叶图。我很可能可以手动执行此操作,但我想知道是否可以自动化该过程?我是否过于雄心勃勃地希望我也可以迭代地命名我的变量?

为了重现该示例,下面是dput 输出。

 dput(head(Commercial_Properties, 5))
structure(list(Rental_Rates = c(13.5, 12, 10.5, 15, 14), Age = c(1, 
14, 16, 4, 11), Op_Expense_Tax = c(5.02, 8.19, 3, 10.7, 8.97), 
    Vacancy_Rate = c(0.14, 0.27, 0, 0.05, 0.07), Total_Sq_Ft = c(123000, 
    104079, 39998, 57112, 60000)), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))

编辑:使用的包:tidyversecar

【问题讨论】:

  • 你能显示使用的包吗
  • 刚刚编辑了问题
  • 没有函数名stem_colnames
  • 我同意。我想做的是使用colnames 函数,所以为了清楚起见,我想做的是stem_ (put the name of my selected column here by using the colnames() function)。所以例如stem_colnames(Commercial_Properties[2])会变成stem_Age' after the for`循环运行
  • 下面发布的解决方案怎么样

标签: r variables naming-conventions


【解决方案1】:

考虑使用cat

for (i in 2:5){cat(names(Commercial_Properties)[i], "\n")
  stem(Commercial_Properties[[i]])
}

-输出

Age 

  The decimal point is 1 digit(s) to the right of the |

  0 | 14
  0 | 
  1 | 14
  1 | 6

Op_Expense_Tax 

  The decimal point is at the |

   2 | 0
   4 | 0
   6 | 
   8 | 20
  10 | 7

Vacancy_Rate 

  The decimal point is 1 digit(s) to the left of the |

  0 | 057
  1 | 4
  2 | 7

Total_Sq_Ft 

  The decimal point is 4 digit(s) to the right of the |

   2 | 
   4 | 07
   6 | 0
   8 | 
  10 | 4
  12 | 3

或者如果我们需要一个函数

f1 <- function(dat, colind) {
   for(i in colind) {
        cat(names(dat)[i], "\n")
        stem(dat[[i]])
   }
   }
f1(Commercial_Properties, 2:5)

或者这可以通过iwalk来完成

library(purrr)
iwalk(Commercial_Properties, ~ {cat(.y, "\n"); stem(.x)})

【讨论】:

  • 不错...cat 做了什么?
  • @dc3rd 它在step 之前打印输入列名。我添加了下一行 (\n),因此 stem 的输出将在下一行打印
  • 酷。感谢您的帮助。是否有一种简单的方法可以按照我想要的方式进行操作,或者我尝试在变量名中使用函数这一事实是否复杂?
  • @dc3rd 更新呢iwalk(Commercial_Properties, ~ {cat(.y, "\n"); stem(.x)})
  • 我以前从未遇到过iwalk 函数。一些新的东西让我去探索。绝对足够我尝试不同的解决方案。我不会再麻烦你了。你对我的帮助超出了我的预期。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
  • 2020-02-05
相关资源
最近更新 更多