将列中的数字因子转换为因子的字符串

问题描述 投票:1回答:1

我有一个数据帧:df

Person    Mood     Age
1         1        16//
2         2        32//
3         3        25//
4         4        22//
5         5        28//
6         1        37//
7         2        40//
8         3        26//
9         4        19//
10        5        37//

我有一个矢量:

Emotions <- c(Happy, Sad, Angry, Upset, Neutral)

我想将列心情中的值转换为矢量情感

Person    Mood     Age
1         happy    16//
2         sad      32//
3         angry    25//
4         upset    22//
5         neutral  28//
6         happy    37//
7         sad      40//
8         angry    26//
9         upset    19//
10        neutral  37//
r dataframe vector factors
1个回答
0
投票

有一种方法使用tidyverse。它有点啰嗦,但有效,可扩展,易于理解:

library(tidyverse)
df %>% 
  select(Mood) %>% # Subset columns to just Mood
  distinct() %>%   # Get unique instances
  bind_cols(tibble(Emotions)) %>% # Convert your vector to a tbl and add as a new column
  merge(df, by = "Mood", all.y = TRUE) %>% # Merge the original df back in
  arrange(Person) %>% # Arrange by Person ID
  select(Person, Mood, Age) # Subset to the desired columns

输出:

   Person Mood  Age
1       1    1 16//
2       2    2 32//
3       3    3 25//
4       4    4 22//
5       5    5 28//
6       6    1 37//
7       7    2 40//
8       8    3 26//
9       9    4 19//
10     10    5 37//
© www.soinside.com 2019 - 2024. All rights reserved.