r - R中的Switch语句根据列值用两个新行替换每一行

标签 r tidyverse

我有以下数据框。

数据

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/

相关文章:

r - 何时使用 na.omit 与 Complete.cases

r - tidyverse 干扰 ggplot2 吗?无法访问map_data

r - 使用字符串查找唯一行并对数据框列的相应值求和

r - 按 1 列以上排序时,Dplyr Arrange 给出错误

r - 如何从尾部提取 - 符号并将其放在数字之前

r - 我想计算 R 中数据框每一行中值/字符的每次出现次数,包括它被其他值/字符包围时

r - 未知累积函数的反函数

Rmarkdown 的 render() + knitr 的 spin() : How to mix code blocks and nested items

r - SF 错误 : Unable to download shapefile in R

r - 将字符串拆分为数字和字符串(有缺失)