运行循环后如何保留标头名称

时间:2019-02-19 23:09:05

标签: r tidyverse

以下脚本生成mtcars数据集每一列的中值,但不包含标题名称。在数据帧上运行for循环后,如何保留标头名称?

output_mtcars <- vector("double", ncol(mtcars))
for(i in seq_along(mtcars)) {
  output_mtcars[[i]] <- mean(mtcars[[i]])
}

3 个答案:

答案 0 :(得分:4)

基数R sapplypurrr::map_dbl都将在此处保留名称:

sapply(mtcars, mean)
purrr::map_dbl(mtcars, mean)

答案 1 :(得分:2)

使用列表而不是向量,我们可以在循环中实现这一点:

output_mtcars <- list("double", ncol(mtcars))
for(i in seq_along(mtcars)) {
  output_mtcars[[i]] <- mean(mtcars[[i]])
  names(output_mtcars[[i]]) <- names(mtcars[i])
}

> output_mtcars
[[1]]
     mpg 
20.09062 

[[2]]
   cyl 
6.1875 

[[3]]
    disp 
230.7219 

[[4]]
      hp 
146.6875 

[[5]]
    drat 
3.596563 

....

或者您也可以在循环后重新命名向量:

output_mtcars <- vector("double")
for(i in seq_along(mtcars)) {
  output_mtcars[[i]] <- mean(mtcars[[i]])
}

names(output_mtcars)<-names(mtcars)

> output_mtcars
       mpg        cyl       disp         hp       drat         wt       qsec 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750 
        vs         am       gear       carb 
  0.437500   0.406250   3.687500   2.812500 

答案 2 :(得分:1)

如果您真的想使用循环,可以使用setNames()

output_mtcars <- setNames(vector("double", ncol(mtcars)), names(mtcars))
for (i in seq_along(mtcars)) {
  output_mtcars[[i]] <- mean(mtcars[[i]])
}

output_mtcars
#       mpg        cyl       disp         hp       drat         wt       qsec         vs         am       gear       carb 
# 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750   0.437500   0.406250   3.687500   2.812500