我有这样的数据:
X snp_id is_severe encoding_1 encoding_2 encoding_0
1 0 GL000191.1-37698 0 0 1 7
3 2 GL000191.1-37922 1 1 0 12我想要做的是在包含前一个snp_id值的每一行之后添加一个新行,如果前面的值为0,则is_sever值为1,如果前面的值为1时(目标是snp_id的每个值在is_severe列中为0和1,而不是0或1(并且每个snp_id将出现两次,一次是is_sever =0,一次是is_sever=1,数据中的所有snp_id值都是唯一的)。此外,encoding_1 & ancoding_2的值为0,encoding_0列将遵循等式:如果在新行中is_severe值为0,则encoding_0 =8,如果在新行中is_severe值为1,则encoding_0为13。
期望产出的例子:
X snp_id is_severe encoding_1 encoding_2 encoding_0
1 0 GL000191.1-37698 0 0 1 7
2 1 GL000191.1-37698 1 0 0 13 <- new row
3 2 GL000191.1-37922 1 1 0 12
4 3 GL000191.1-37922 0 0 0 8 <- new row我在这里看到了类似的QA:How can I add rows to an R data frame every other row?,但是我需要做更多的数据操作,不幸的是,这个解决方案并没有解决我的问题。(谢谢:)
发布于 2022-10-27 11:25:03
这里有两个选择。1)拆分和映射,2)复制和绑定
library(tidyverse)
dat <- read_table("snp_id is_severe encoding_1 encoding_2 encoding_0
GL000191.1-37698 0 0 1 7
GL000191.1-37922 1 1 0 12")
dat |>
group_split(snp_id) |>
map_dfr(~add_row(.x,
snp_id = .x$snp_id,
is_severe = 1 - (.x$is_severe == 1),
encoding_1 = 0,
encoding_2 = 0,
encoding_0 = ifelse(.x$is_severe == 1, 8, 13)))
#> # A tibble: 4 x 5
#> snp_id is_severe encoding_1 encoding_2 encoding_0
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 GL000191.1-37698 0 0 1 7
#> 2 GL000191.1-37698 1 0 0 13
#> 3 GL000191.1-37922 1 1 0 12
#> 4 GL000191.1-37922 0 0 0 8或
library(tidyverse)
bind_rows(dat,
dat |>
mutate(is_severe = 1 - (is_severe == 1),
across(c(encoding_1, encoding_2), ~.*0),
encoding_0 = ifelse(is_severe == 1, 13, 8))) |>
arrange(snp_id)
#> # A tibble: 4 x 5
#> snp_id is_severe encoding_1 encoding_2 encoding_0
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 GL000191.1-37698 0 0 1 7
#> 2 GL000191.1-37698 1 0 0 13
#> 3 GL000191.1-37922 1 1 0 12
#> 4 GL000191.1-37922 0 0 0 8发布于 2022-10-27 11:18:30
虚拟数据:
df <- data.frame(
a = letters[1:4],
is_severe = sample(c(0,1), 4, TRUE),
encoding1 = sample(c(0,1), 4, TRUE),
encoding2 = sample(c(0,1), 4, TRUE),
encoding0 = 1:4
)您可以复制数据,进行计算,并与原始数据绑定(之后进行所需的行排列):
df_copy <- df
df_copy$is_severe <- 1 - df_copy$is_severe
df_copy[, c("encoding1", "encoding2")] <- 0
df_copy$encoding0 <- ifelse(df_copy$is_severe == 0, 8 , 13)
rbind(df, df_copy)[rep(seq_len(nrow(df)), each = 2) + rep(c(0, nrow(df)), times = nrow(df)),]https://stackoverflow.com/questions/74221077
复制相似问题