数据
demo <- structure(list(Performance = c("Performance-3", "Performance-2",
"Performance-2", "Performance-1", "Performance-7", "Performance-8",
"Performance-4", "Performance-1", "Performance-1", "Performance-1",
"Performance-2", "Performance-1", "Performance-7", "Performance-2",
"Performance-1", "Performance-2", "Performance-3", "Performance-4",
"Performance-8", "Performance-9", "Performance-8", "Performance-1",
"Performance-7", "Performance-3", "Performance-2", "Performance-3",
"Performance-4", "Performance-9", "Performance-3", "Performance-8",
"Performance-2", "Performance-8", "Performance-2", "Performance-7",
"Performance-3", "Performance-3", "Performance-3", "Performance-7",
"Performance-7", "Performance-4", "Performance-2", "Performance-2",
"Performance-2", "Performance-1", "Performance-2", "Performance-4",
"Performance-1", "Performance-2", "Performance-7", "Performance-4"
), ItemValue = c(4L, 5L, 3L, 5L, 2L, 1L, 5L, 5L, 4L, 5L, 5L,
4L, 1L, 5L, 5L, 4L, 4L, 4L, 2L, 2L, 3L, 5L, 3L, 4L, 4L, 3L, 5L,
1L, 4L, 2L, 5L, 2L, 4L, 1L, 4L, 5L, 3L, 1L, 1L, 4L, 4L, 5L, 3L,
4L, 5L, 5L, 5L, 5L, 2L, 4L)), row.names = c(3583L, 479L, 634L,
578L, 3759L, 3496L, 9595L, 4052L, 7984L, 5228L, 131L, 1014L,
4836L, 3912L, 298L, 10027L, 258L, 79L, 6449L, 7526L, 2744L, 4403L,
902L, 3808L, 561L, 3385L, 4232L, 7962L, 9361L, 959L, 2171L, 5896L,
1258L, 8800L, 4591L, 4630L, 9347L, 2902L, 9738L, 9143L, 3990L,
10488L, 9581L, 10905L, 9859L, 8787L, 8626L, 6901L, 760L, 3290L
), class = "data.frame")我想逆转性能值-7,使5变成1 . 1变成5
我通过以下方式使用ifelse完成了这项工作:
demo %>% mutate(ItemValue = ifelse(Performance == "Performance-7" & ItemValue == 5, 1,
ifelse(Performance == "Performance-7" & ItemValue == 4, 2,
ifelse(Performance == "Performance-7" & ItemValue == 3, 3,
ifelse(Performance == "Performance-7" & ItemValue == 2, 4,
ifelse(Performance == "Performance-7" & ItemValue == 1, 5, ItemValue))))))但是正如你所看到的,有很多ifelse。我试着使用recode,但是找不出另一个字段的条件。
发布于 2020-05-16 15:24:56
让我们翻译一下:
@library(tidyverse)
demo2 <- demo %>%
left_join(transl <- tibble(ItemValue = 1:5, NewItemValue = 5:1),
by = "ItemValue")瞧一瞧
head(demo2)
Performance ItemValue NewItemValue
1 Performance-3 4 2
2 Performance-2 5 1
3 Performance-2 3 3
4 Performance-1 5 1
5 Performance-7 2 4
6 Performance-8 1 5把它清理干净
answer <- demo2 %>%
mutate(ItemValue = ifelse(Performance == "Performance-7",
NewItemValue, ItemValue)) %>%
select(Performance, ItemValue)
head(answer)
Performance ItemValue
1 Performance-3 4
2 Performance-2 5
3 Performance-2 3
4 Performance-1 5
5 Performance-7 4
6 Performance-8 1https://stackoverflow.com/questions/61839010
复制相似问题