r - 向重复一行并替换 2 个条目的数据框添加一行
问题描述
我想将行添加到数据框(或小标题)作为数据输入项目的一部分。我需要:
- 在一列中查找包含特定值的一行(obsid)
- 复制该行。但是,替换“word”列中的值。
- 将新行附加到数据框
我想写一个让它变得简单的函数。当我编写函数时,它不会添加新行。我可以打印出答案。但它不会改变基本数据框
如果我在没有功能的情况下这样做,它也可以工作。
为什么函数不会添加行?
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")
解决方案
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
推荐阅读
- tensorflow - 将 Tensorflow 冻结的 .pb 模型转换为 keras 模型
- python - 绘制存储在元组列表中的方形颜色?
- angular - ngrx (Angular) 中的状态管理实现
- python - 如何为 Pandas 系列表达式指定类型提示
- python - 如何使用 sklearn 预处理管道中的标签?
- objective-c - 如何为 AppleTV 和 MacOSX 统一构建一个 Objective-C 原生插件
- amazon-web-services - 改进 AppStream 2.0 实例中的视频播放?
- vivado - 为 16x16 位乘法器的测试平台生成输入数字
- ios - 在应用程序购买中,节点后端中的 ios 收据验证失败,响应状态为 21002 - 收据数据属性中的数据格式错误
- asp.net - 如何在按钮单击时转到下拉列表中的下一个项目