使用 *plyr 更改列名,其中映射由另一个数据框的两列给出
Change column names using *plyr where the mapping is given by two columns of another data frame
我有一个简单的数据框a
x y
1 1 11
2 2 22
3 3 33
还有一个b
old new
1 x haha
2 y hoho
这给出了旧列名到新列名的映射。我想要以下数据框 c
.
haha hoho
1 1 11
2 2 22
3 3 33
请注意,实际的 a
有很多列,并且 b
中两列的映射不是直接的。此外,b
的行可能 与 a
.
的列的顺序不同
可以使用plyr/dplyr
吗? python 中的类似内容:Changing dataframe columns names by columns from another dataframe python?
这是使用!!
的好机会:
library(tidyverse)
data <- tribble(
~x, ~y,
1, 11,
2, 22,
3, 33
)
name_tbl <- tribble(
~old, ~new,
"x", "haha",
"y", "hoho"
)
(name_pairs <- with(name_tbl, set_names(old, new)))
#> haha hoho
#> "x" "y"
rename(data, !!name_pairs)
#> # A tibble: 3 x 2
#> haha hoho
#> <dbl> <dbl>
#> 1 1 11
#> 2 2 22
#> 3 3 33
由 reprex package (v0.3.0)
于 2019-10-21 创建
rename()
使用名称-值对(以新名称作为名称),所以我们只需要 1) 获取旧名称的向量,2) 给它新名称的名称,和 3) 使用命名向量调用 rename()
,不加引号,因为我们将这些对作为对象值而不是语法传递。
我有一个简单的数据框a
x y
1 1 11
2 2 22
3 3 33
还有一个b
old new
1 x haha
2 y hoho
这给出了旧列名到新列名的映射。我想要以下数据框 c
.
haha hoho
1 1 11
2 2 22
3 3 33
请注意,实际的 a
有很多列,并且 b
中两列的映射不是直接的。此外,b
的行可能 与 a
.
可以使用plyr/dplyr
吗? python 中的类似内容:Changing dataframe columns names by columns from another dataframe python?
这是使用!!
的好机会:
library(tidyverse)
data <- tribble(
~x, ~y,
1, 11,
2, 22,
3, 33
)
name_tbl <- tribble(
~old, ~new,
"x", "haha",
"y", "hoho"
)
(name_pairs <- with(name_tbl, set_names(old, new)))
#> haha hoho
#> "x" "y"
rename(data, !!name_pairs)
#> # A tibble: 3 x 2
#> haha hoho
#> <dbl> <dbl>
#> 1 1 11
#> 2 2 22
#> 3 3 33
由 reprex package (v0.3.0)
于 2019-10-21 创建rename()
使用名称-值对(以新名称作为名称),所以我们只需要 1) 获取旧名称的向量,2) 给它新名称的名称,和 3) 使用命名向量调用 rename()
,不加引号,因为我们将这些对作为对象值而不是语法传递。