首页 > 解决方案 > 向重复一行并替换 2 个条目的数据框添加一行

问题描述

我想将行添加到数据框(或小标题)作为数据输入项目的一部分。我需要:

  1. 在一列中查找包含特定值的一行(obsid)
  2. 复制该行。但是,替换“word”列中的值。
  3. 将新行附加到数据框

我想写一个让它变得简单的函数。当我编写函数时,它不会添加新行。我可以打印出答案。但它不会改变基本数据框

如果我在没有功能的情况下这样做,它也可以工作。

为什么函数不会添加行?

df <- tibble(obsid = c("a","b" , "c", "d"), b=c("a", "a", "b", "b"), word= c("what", "is", "the", "answer"))
df$main <- 1

addrow <- function(id, newword) {
  rowtoadd <- df %>%
    filter(obsid== id &  main==1) %>% 
    mutate(word=replace(word, main==1, newword)) %>% 
    mutate(main=replace(main, word==newword, 0)) 
  df <- bind_rows(df, rowtoadd) 
  print(rowtoadd) 
  print(filter(df, df$obsid== id))}

addrow("a", "xxx")

标签: rdplyr

解决方案


R 对象通常不会修改自身,您需要将结果变形return()以返回该数据帧的修改副本。

将您的功能更改为:

df <- tibble(obsid = c("a","b" , "c", "d"), b=c("a", "a", "b", "b"), word= c("what", "is", "the", "answer"))
df$main <- 1

addrow <- function(id, newword) {
    rowtoadd <- df %>%
        filter(obsid== id &  main==1) %>% 
        mutate(word=replace(word, main==1, newword)) %>% 
        mutate(main=replace(main, word==newword, 0)) 
    df <- bind_rows(df, rowtoadd)
    return(df)
}
> addrow("a", "xxx")
# A tibble: 5 x 4
  obsid b     word    main
  <chr> <chr> <chr>  <dbl>
1 a     a     what       1
2 b     a     is         1
3 c     b     the        1
4 d     b     answer     1
5 a     a     xxx        0

推荐阅读