【发布时间】:2017-10-19 00:04:58
【问题描述】:
我得到了下面的data.frame df,它有很长的变量名。
每个名称的第一部分是主要类别(岩石、土壤、土地利用),通常由多个名称组成的第二部分是等级(例如对于岩石,两个等级是sandstone mudstone basalt chert limestone和sandstone conglomerate coquina tephra )。
> df
# A tibble: 5 x 2
`rock_sandstone conglomerate coquina tephra` `rock_sandstone mudstone basalt chert limestone`
<dbl> <dbl>
1 0.000000 18.774037
2 41.968310 30.276509
3 32.804031 0.000000
4 8.669436 3.092062
5 32.937377 19.894776
我想通过使用每个单词的第一个字母来缩短变量名称,如下所示。
我可以使用例如dplyr::rename 来做到这一点。但是,我有 97 个变量,我想对 20 个具有不同变量名的 data.frames 执行相同的操作。我想知道是否有更快的方法。
library(dplyr)
df <- df %>% rename("r_sccat" = 'rock_sandstone conglomerate coquina tephra',
"r_smbcl" = "rock_sandstone mudstone basalt chert limestone")
> df
# A tibble: 5 x 2
r_sccat r_smbcl
<dbl> <dbl>
1 0.000000 18.774037
2 41.968310 30.276509
3 32.804031 0.000000
4 8.669436 3.092062
5 32.937377 19.894776
数据
> dput(df)
structure(list(`rock_sandstone conglomerate coquina tephra` = c(0,
41.9683095321332, 32.8040311360418, 8.66943642122745, 32.9373770476129
), `rock_sandstone mudstone basalt chert limestone` = c(18.7740373237074,
30.2765089609693, 0, 3.09206176664796, 19.8947759845006)), row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("rock_sandstone conglomerate coquina tephra",
"rock_sandstone mudstone basalt chert limestone"))
【问题讨论】:
标签: r