英文:
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<-`(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
答案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"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论