gpt4 book ai didi

r - 使用 dplyr 修改列中的一行

转载 作者:行者123 更新时间:2023-12-05 08:46:23 25 4
gpt4 key购买 nike

说我有这两个tibbles

library(dplyr)
library(lubridate)

my_date <- as_date(c("2021-10-30","2021-10-29","2021-10-28"))
my_t1 <- tibble(date = my_date) %>%
mutate("col1" = NA,
"col2" = NA,
"col3" = NA,
"col4" = NA)
my_t2 <- tibble("column" = c("col1","col2","col3","col4"),
"value" = c(10,20,30,40))

所以

> my_t1
# A tibble: 3 × 5
date col1 col2 col3 col4
<date> <lgl> <lgl> <lgl> <lgl>
1 2021-10-30 NA NA NA NA
2 2021-10-29 NA NA NA NA
3 2021-10-28 NA NA NA NA

> my_t2
# A tibble: 4 × 2
column value
<chr> <dbl>
1 col1 10
2 col2 20
3 col3 30
4 col4 40

我想复制的值

my_t2 %>% select(value)

进入 my_t1 的特定行,比如中间一行(date == "2021-10-29")。我想避免对每个元素一个一个地做(即基数 R),这样 my_t1 就变成了

# A tibble: 3 × 5
date col1 col2 col3 col4
<date> <lgl> <lgl> <lgl> <lgl>
1 2021-10-30 NA NA NA NA
2 2021-10-29 10 20 30 40
3 2021-10-28 NA NA NA NA

最佳答案

我们可以使用 matchcur_column 将第二行替换为“my_t2”中相应的“column”值

library(dplyr)
my_t1_new <- my_t1 %>%
mutate(across(-date, ~ replace(., date == "2021-10-29",
my_t2$value[match(cur_column(), my_t2$column)])))

-输出

my_t1_new
# A tibble: 3 × 5
date col1 col2 col3 col4
<date> <dbl> <dbl> <dbl> <dbl>
1 2021-10-30 NA NA NA NA
2 2021-10-29 10 20 30 40
3 2021-10-28 NA NA NA NA

如果列是有序的,base R会更容易

my_t1_new <- as.data.frame(my_t1)
my_t1_new[2, -1] <- my_t2$value

关于r - 使用 dplyr 修改列中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69781432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com