[英]Change long variable names in data.frame
我在下面的data.frame df
中拥有长的变量名。
每个名称的第一部分是主要类别(岩石,土壤,土地利用),第二部分通常由几个名称组成,即级别(例如,对于岩石,两个级别是sandstone mudstone basalt chert limestone
, sandstone conglomerate coquina tephra
sandstone mudstone basalt chert limestone
, 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"))
有点难看,但是abbreviate
和一些正则表达式替换将使您到达那里:
names(df) <- sub("^(.)", "\\1_", abbreviate(gsub("_", " ", names(df))))
df
## A tibble: 5 × 2
# r_scct 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
我不熟悉缩写,但是可以通过一些正则表达式直接实现相同的缩写:
names( df ) <- gsub( ' ', "", gsub( "([a-z])([a-z]+)", "\\1", names( df ) ) )
使用magrittr可以使语法更简洁:
require( magrittr )
names( df ) %<>%
gsub( "([a-z])([a-z]+)", "\\1", . ) %>%
gsub( " ", "", . )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.