我有以下数据框。
数据
df <- structure(list(ID = structure(1:10, .Label = c("7519", "7522",
"7525", "7526", "7527", "7530", "7537", "7538", "7541", "7542"
), class = "factor"), MN = c(2, 1, 0, 1, 2, 1, 0, 1, 2, 0)), class = "data.frame", row.names = c(NA,
-10L))
ID MN
1 7519 2
2 7522 1
3 7525 0
4 7526 1
5 7527 2
6 7530 1
7 7537 0
8 7538 1
9 7541 2
10 7542 0
我想将其转换为一个基于 MN 的 20 行新数据框。 MN有3个条件:0,1,2
如果MN==0,我想加M=1,N=0
如果MN==1,我想加M=1,N=1
如果MN==2,我想加M=0,N=1
期望的是:
结果
ID name value
1 7519 M 0
2 7519 N 1
3 7522 M 1
4 7522 N 1
5 7525 M 1
6 7525 N 0
7 7526 M 1
8 7526 N 1
9 7527 M 0
10 7527 N 1
11 7530 M 1
12 7530 N 1
13 7537 M 1
14 7537 N 0
15 7538 M 1
16 7538 N 0
17 7541 M 0
18 7541 N 1
19 7542 M 1
20 7542 N 0
最佳答案
这是一个基于join和转长格式的方法。
library(tidyverse)
lookup <- tibble(
MN = 0:2,
M = c(1, 1, 0),
N = c(0, 1, 1)
)
df2 <- df %>%
left_join(lookup, by = "MN") %>%
select(-MN) %>%
pivot_longer(cols = -ID)
df2
# # A tibble: 20 x 3
# ID name value
# <fct> <chr> <dbl>
# 1 7519 M 0
# 2 7519 N 1
# 3 7522 M 1
# 4 7522 N 1
# 5 7525 M 1
# 6 7525 N 0
# 7 7526 M 1
# 8 7526 N 1
# 9 7527 M 0
# 10 7527 N 1
# 11 7530 M 1
# 12 7530 N 1
# 13 7537 M 1
# 14 7537 N 0
# 15 7538 M 1
# 16 7538 N 1
# 17 7541 M 0
# 18 7541 N 1
# 19 7542 M 1
# 20 7542 N 0
关于r - R中的Switch语句根据列值用两个新行替换每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60387207/