如何在R中有条件地复制和编辑行

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

How to conditionally duplicate and edit rows in r

问题

需要向数据框中添加两行,这两行的值与现有行相同。例如,下面的情况下,我需要添加 "a" = 3,其 "b" 值与 "a" = 2 的行相同,从这样的结构:

a b
1 higha
1 lowa
2 highb
2 lowb

到这样的结构:

a b
1 higha
1 lowa
2 highb
2 lowb
3 highb
3 lowb
英文:

I need to add 2 rows to a dataframe that have the same values as existing rows. For example, below I would need to add "a" = 3 with the same "b" values as "a" = 2, going from this:

| a | b     |
| --| ------|
| 1 | higha |
| 1 | lowa  |
| 2 | highb |
| 2 | lowb  |

to this:

| a | b     |
| --| ------|
| 1 | higha |
| 1 | lowa  |
| 2 | highb |
| 2 | lowb  |
| 3 | highb |
| 3 | lowb  |

答案1

得分: 2

以下是翻译好的部分:

`rownames<-`(rbind(df, within(df[df$a == 2,], a <- 3)), NULL)
#>   a     b
#> 1 1 higha
#> 2 1  lowa
#> 3 2 highb
#> 4 2  lowb
#> 5 3 highb
#> 6 3  lowb
英文:

A one-liner in base R would be:

`rownames&lt;-`(rbind(df, within(df[df$a == 2,], a &lt;- 3)), NULL)
#&gt;   a     b
#&gt; 1 1 higha
#&gt; 2 1  lowa
#&gt; 3 2 highb
#&gt; 4 2  lowb
#&gt; 5 3 highb
#&gt; 6 3  lowb

答案2

得分: 1

Sure, here is the translated code:

可能会使用

```R
library(dplyr)
library(tidyr)
df %>%
   uncount((a == 2) + 1) %>%
   mutate(a = replace(a, duplicated(b) & a == 2, 3)) %>%
   arrange(a)

-output

# A tibble: 6 × 2
      a b    
  <dbl> <chr>
1     1 higha
2     1 lowa 
3     2 highb
4     2 lowb 
5     3 highb
6     3 lowb 

或者使用 base R

i1 <- df$a == 2
df[nrow(df) + seq_len(sum(i1)),] <- data.frame(a = 3, b = df$b[i1])

data

df <- data.frame(a = rep(1:2, each = 2), 
   b = c("higha", "lowa", "highb", "lowb"))

Please note that I've only translated the code parts, as you requested.

<details>
<summary>英文:</summary>

We may use

library(dplyr)
library(tidyr)
df %>%
uncount((a == 2)+1) %>%
mutate(a = replace(a, duplicated(b) & a == 2, 3)) %>%
arrange(a)


-output

A tibble: 6 × 2

  a b    

<dbl> <chr>
1 1 higha
2 1 lowa
3 2 highb
4 2 lowb
5 3 highb
6 3 lowb


---

Or with `base R`

i1 <- df$a == 2
df[nrow(df) + seq_len(sum(i1)),] <- data.frame(a = 3, b = df$b[i1])


### data

df <- data.frame(a = rep(1:2, each = 2),
b = c("higha", "lowa", "highb", "lowb"))

huangapple
  • 本文由 发表于 2023年2月7日 04:56:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366506.html
匿名

发表评论

匿名网友

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

确定