在同一行的不同列中,基于同一行中存在的值,为不同行添加新列。

huangapple go评论60阅读模式
英文:

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 = &quot;_&quot;)
  row   ind
1   1 F1_F2
2   2 F1_F3
3   3 F1_F4

df &lt;- structure(list(F1 = c(1L, 1L, 1L), F2 = c(1L, NA, NA), F3 = c(NA, 
1L, NA), F4 = c(NA, NA, 1L)), class = &quot;data.frame&quot;, row.names = c(NA, 
-3L))

答案2

得分: 0

此解决方案利用 dplyr::mutatedplyr::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),
) |&gt;
  mutate(across(everything(),
                \(x) ifelse(x == 1, cur_column(), NA))) |&gt;
  unite(&quot;trt&quot;, remove = FALSE, na.rm = TRUE)
#&gt; # A tibble: 3 &#215; 5
#&gt;   trt   F1    F2    F3    F4   
#&gt;   &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;
#&gt; 1 F1_F2 F1    F2    &lt;NA&gt;  &lt;NA&gt; 
#&gt; 2 F1_F3 F1    &lt;NA&gt;  F3    &lt;NA&gt; 
#&gt; 3 F1_F4 F1    &lt;NA&gt;  &lt;NA&gt;  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),
) |&gt;
  mutate(across(everything(),
                \(x) ifelse(x == 1, cur_column(), NA))) |&gt;
  unite(&quot;trt&quot;, remove = FALSE, na.rm = TRUE)
#&gt; # A tibble: 3 &#215; 5
#&gt;   trt   F1    F2    F3    F4   
#&gt;   &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;
#&gt; 1 F1_F2 F1    F2    &lt;NA&gt;  &lt;NA&gt; 
#&gt; 2 F1_F3 F1    &lt;NA&gt;  F3    &lt;NA&gt; 
#&gt; 3 F1_F4 F1    &lt;NA&gt;  &lt;NA&gt;  F4

huangapple
  • 本文由 发表于 2023年6月1日 23:13:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定