[英]How to rename columns in a nested tibble based on the value of another column
Sometimes I change column names of nested tibble depending on the value of another column. 有时我会根据另一列的值更改嵌套tibble的列名。
I can do it preparing a function using in map()
. 我可以使用
map()
来准备一个函数。
library(tidyverse)
# sample data
d <- tibble(col1 = 1:8, col2 = 11:18, group = letters[rep(1:2, each = 4)]) %>%
nest(-group)
f <- function(data, group) rename(data, !!paste0(group, "_col1") := col1)
# Run
desired_output <- d %>%
mutate(data = map2(data, group, f))
names(desired_output$data[[1]]) # "a_col1" "col2" # work
I want to do it by anonymous function, but it doesn't work. 我想通过匿名函数来做,但它不起作用。 Is there a way to do like
mutate(map(rename(!!a := b)))
with anonymous function? 有没有办法像使用匿名函数
mutate(map(rename(!!a := b)))
? Thank you for any advice. 谢谢你的任何建议。
d %>%
mutate(data2 = map2(data, group,
function(data, group) {
data %>%
rename(!!paste0(group, "_col1") := col1)
}))
# Error in paste0(group, "_col1") : object 'group' not found
I am not sure what you exactly mean by anonymous function but here is a way to do this without having to assign the function f
to a variable: 我不确定你的匿名函数究竟是什么意思,但这里有一种方法可以做到这一点,而无需将函数
f
赋值给变量:
d %>%
mutate(data = map2(data, group, ~rename_at(.x, 1, function(z) paste(.y, z, sep = "_"))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.