如何在 R 中手动对列出的数据框列中的级别进行排序?
How can I sort levels in columns of listed dataframes manually in R?
我有三个数据框类似于:
Value Time Colour Fruit
1 9.0 1 Orange Apple
2 9.5 2 Orange Apple
3 10.0 1 Red Apple
4 9.0 2 Blue Apple
5 9.5 1 Blue Apple
6 10.0 2 Blue Pear
7 1.0 1 Blue Pear
8 2.0 2 Red Pear
9 3.0 1 Red Pear
10 2.0 2 Orange Pear
11 1.0 1 Blue Mango
12 3.0 2 Blue Mango
13 2.0 2 Red Mango
14 3.0 1 Red Mango
15 2.0 2 Orange Mango
16 1.0 1 Blue Banana
17 3.0 2 Blue Banana
18 2.0 2 Red Banana
19 3.0 1 Red Banana
20 2.0 2 Orange Banana
...在 my_list 中列出:
my_list<- list(df1=df1, df2=df2, df3=df3)
用于稍后绘制数据(使用 facet_grid 分组条形图)我想重新调整 Fruit 和 Color 的值,就像我可以使用 fct_relevel 对单个数据帧做的那样:
Data <- Data %>%
mutate(Colour = fct_relevel(Colour,"Blue", "Red", "Orange")) %>%
mutate(Fruit = fct_relevel(Fruit, "Apple", "Mango", "Banana", "Pear"))
感谢您的帮助!
您可以使用 lapply 循环遍历 df 列表,假设 df 的级别都相同。
my_list <- lapply(my_list, function(x){ x %>%
mutate(Colour = fct_relevel(Colour,"Blue", "Red", "Orange"),
Fruit = fct_relevel(Fruit, "Apple", "Mango", "Banana", "Pear"))
})
由于您使用的是 dplyr,一种方法是使用 map
from purrr
:
library(dplyr)
library(purrr)
mylist <- my_list %>%
map(~ .x %>%
mutate(Colour = fct_relevel(Colour,"Blue", "Red", "Orange")) %>%
mutate(Fruit = fct_relevel(Fruit, "Apple", "Mango", "Banana", "Pear")))
我有三个数据框类似于:
Value Time Colour Fruit
1 9.0 1 Orange Apple
2 9.5 2 Orange Apple
3 10.0 1 Red Apple
4 9.0 2 Blue Apple
5 9.5 1 Blue Apple
6 10.0 2 Blue Pear
7 1.0 1 Blue Pear
8 2.0 2 Red Pear
9 3.0 1 Red Pear
10 2.0 2 Orange Pear
11 1.0 1 Blue Mango
12 3.0 2 Blue Mango
13 2.0 2 Red Mango
14 3.0 1 Red Mango
15 2.0 2 Orange Mango
16 1.0 1 Blue Banana
17 3.0 2 Blue Banana
18 2.0 2 Red Banana
19 3.0 1 Red Banana
20 2.0 2 Orange Banana
...在 my_list 中列出:
my_list<- list(df1=df1, df2=df2, df3=df3)
用于稍后绘制数据(使用 facet_grid 分组条形图)我想重新调整 Fruit 和 Color 的值,就像我可以使用 fct_relevel 对单个数据帧做的那样:
Data <- Data %>%
mutate(Colour = fct_relevel(Colour,"Blue", "Red", "Orange")) %>%
mutate(Fruit = fct_relevel(Fruit, "Apple", "Mango", "Banana", "Pear"))
感谢您的帮助!
您可以使用 lapply 循环遍历 df 列表,假设 df 的级别都相同。
my_list <- lapply(my_list, function(x){ x %>%
mutate(Colour = fct_relevel(Colour,"Blue", "Red", "Orange"),
Fruit = fct_relevel(Fruit, "Apple", "Mango", "Banana", "Pear"))
})
由于您使用的是 dplyr,一种方法是使用 map
from purrr
:
library(dplyr)
library(purrr)
mylist <- my_list %>%
map(~ .x %>%
mutate(Colour = fct_relevel(Colour,"Blue", "Red", "Orange")) %>%
mutate(Fruit = fct_relevel(Fruit, "Apple", "Mango", "Banana", "Pear")))