我有5个数据帧。我想重新编码所有以"_comfort", "_agree"one_answers"effective"结尾的变量对每个数据帧使用相同的规则。实际上,每列中的值都是1:5,我希望将5重新编码为1,4为2,2为4,5为1(3将保持不变)。
我不希望最终结果是一个合并的数据集,而是在所有5个独立的数据帧上应用相同的重新编码规则。为简单起见,我们假设我有两个数据帧:
df1 <- data.frame(a_comfort = c(1, 2, 3, 4, 5),
b_comfort = c(1, 2, 3, 4, 5),
c_effective = c(1, 2, 3, 4, 5))
df2 <- data.frame(a_comfort = c(1, 2, 3, 4, 5),
b_comfort = c(1, 2, 3, 4, 5),
c_effective = c(1, 2, 3, 4, 5))
我要的是:
df1 <- data.frame(a_comfort = c(5, 4, 3, 2, 1),
b_comfort = c(5, 4, 3, 2, 1),
c_effective = c(5, 4, 3, 2, 1))
df2 <- data.frame(a_comfort = c(5, 4, 3, 2, 1),
b_comfort = c(5, 4, 3, 2, 1),
c_effective = c(5, 4, 3, 2, 1))
通常,我会使用dplyr
的mutate_at
和ends_with
来实现我的目标,但是在多个数据帧中使用这种方法并没有成功。我认为purr和dplyr包的组合可以工作,但还没有确定确切的技术。
提前感谢您的帮助!
可以在循环中使用get()
和assign()
:
library(dplyr)
for (df_name in c("df1", "df2")) {
df <- mutate(
get(df_name),
across(
ends_with(c("_comfort", "_agree", "_effective")),
(x) 6 - x
)
)
assign(df_name, df)
}
结果:
#> df1
a_comfort b_comfort c_effective
1 5 5 5
2 4 4 4
3 3 3 3
4 2 2 2
5 1 1 1
#> df2
a_comfort b_comfort c_effective
1 5 5 5
2 4 4 4
3 3 3 3
4 2 2 2
5 1 1 1
但是,请注意,将多个相关数据帧保存在一个列表中通常比在全局环境中保持松散要好(参见)。在这种情况下,您可以使用purrr::map()
(或base::lapply()
):
library(dplyr)
library(purrr)
dfs <- list(df1, df2)
dfs <- map(
dfs,
(df) mutate(
df,
across(
ends_with(c("_comfort", "_agree", "_effective")),
(x) 6 - x
)
)
)
结果:
#> dfs
[[1]]
a_comfort b_comfort c_effective
1 5 5 5
2 4 4 4
3 3 3 3
4 2 2 2
5 1 1 1
[[2]]
a_comfort b_comfort c_effective
1 5 5 5
2 4 4 4
3 3 3 3
4 2 2 2
5 1 1 1
您可以使用ls(pattern = 'df\d+')
查找名称与某个模式匹配的所有对象。然后将它们存储到list
中,并传递给purrr::map
或lapply
进行重新编码。
library(dplyr)
df.lst <- purrr::map(
mget(ls(pattern = 'df\d+')),
~ .x %>% mutate(6 - across(ends_with(c("_comfort", "_agree", "effective"))))
)
# $df1
# a_comfort b_comfort c_effective
# 1 5 5 5
# 2 4 4 4
# 3 3 3 3
# 4 2 2 2
# 5 1 1 1
#
# $df2
# a_comfort b_comfort c_effective
# 1 5 5 5
# 2 4 4 4
# 3 3 3 3
# 4 2 2 2
# 5 1 1 1
您可以通过list2env()
从列表中进一步覆盖工作区中的这些数据框。
list2env(df.lst, .GlobalEnv)
请尝试下面的代码,我将列转换为因子,然后重新编码
数据a_comfort b_comfort c_effective
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
library(tidyverse)
df1 %>% mutate(across(c(ends_with('comfort'),ends_with('effective')), ~ factor(.x, levels=c('1','2','3','4','5'), labels=c('5','4','3','2','1'))))
输出a_comfort b_comfort c_effective
1 5 5 5
2 4 4 4
3 3 3 3
4 2 2 2
5 1 1 1
library(tidyverse)
df1 %>% mutate(across(c(ends_with('comfort'),ends_with('effective')), ~ factor(.x, levels=c('1','2','3','4','5'), labels=c('5','4','3','2','1'))))
a_comfort b_comfort c_effective
1 5 5 5
2 4 4 4
3 3 3 3
4 2 2 2
5 1 1 1