我有一个数据框: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//
答案 0 :(得分:0)
有一种使用tidyverse
的方法。有点long,但是可以用,可以扩展并且易于理解:
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//