英文:
Adding new column for different rows based on the values present in the same row for a different column
问题
我有一个包含不同因素组合的数据框。每个因素都在其列中表示(见下文)
我想在最后添加一个新列,如下所示
如何在R中进行条件合并以创建此列。任何建议都将不胜感激!
英文:
I have a dataframe with different combination of factors. each factor is presented in its column (see below)
F1 F2 F3 F4
1 1
1 1
1 1
I want to add a new column at the end like below
F1 F2 F3 F4 trt
1 1 F1_F2
1 1 F1_F3
1 1 F1_F4
How do I create this column with conditional merging in R. Any advice would be appreciated!
答案1
得分: 0
aggregate(ind ~ row, na.omit(cbind(row = c(row(df)), stack(df))), paste, collapse = "_")
row ind
1 1 F1_F2
2 2 F1_F3
3 3 F1_F4
df <- structure(list(F1 = c(1L, 1L, 1L), F2 = c(1L, NA, NA), F3 = c(NA,
1L, NA), F4 = c(NA, NA, 1L)), class = "data.frame", row.names = c(NA,
-3L))
英文:
aggregate(ind~row, na.omit(cbind(row = c(row(df)), stack(df))), paste, collapse = "_")
row ind
1 1 F1_F2
2 2 F1_F3
3 3 F1_F4
df <- structure(list(F1 = c(1L, 1L, 1L), F2 = c(1L, NA, NA), F3 = c(NA,
1L, NA), F4 = c(NA, NA, 1L)), class = "data.frame", row.names = c(NA,
-3L))
答案2
得分: 0
此解决方案利用 dplyr::mutate
与 dplyr::across
结合,将所有值为 1
的替换为列名。然后可以使用 tidyr::unite()
创建 trt
列。
library(tidyverse)
tibble(
F1 = rep(1, 3),
F2 = c(1, 0, 0),
F3 = c(0, 1, 0),
F4 = c(0, 0, 1),
) |>
mutate(across(everything(),
\(x) ifelse(x == 1, cur_column(), NA))) |>
unite("trt", remove = FALSE, na.rm = TRUE)
#> # A tibble: 3 × 5
#> trt F1 F2 F3 F4
#> <chr> <chr> <chr> <chr> <chr>
#> 1 F1_F2 F1 F2 <NA> <NA>
#> 2 F1_F3 F1 <NA> F3 <NA>
#> 3 F1_F4 F1 <NA> <NA> F4
希望这对你有所帮助。
英文:
This solution utilizes dplyr::mutate
in combination with dplyr::across
to replace all 1
values with the column name. tidyr::unite()
can then be used to create the trt
column.
library(tidyverse)
tibble(
F1 = rep(1, 3),
F2 = c(1, 0, 0),
F3 = c(0, 1, 0),
F4 = c(0, 0, 1),
) |>
mutate(across(everything(),
\(x) ifelse(x == 1, cur_column(), NA))) |>
unite("trt", remove = FALSE, na.rm = TRUE)
#> # A tibble: 3 × 5
#> trt F1 F2 F3 F4
#> <chr> <chr> <chr> <chr> <chr>
#> 1 F1_F2 F1 F2 <NA> <NA>
#> 2 F1_F3 F1 <NA> F3 <NA>
#> 3 F1_F4 F1 <NA> <NA> F4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论