使用向量中的值在数据框中添加行 [英] Use values in vector to add rows in dataframe

查看:35
本文介绍了使用向量中的值在数据框中添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称向量:

nums = 1:5
names = paste("name_", nums, sep="")

还有一个数据框,其中 col1 包含名称中列出的值的子集:

And a data frame where col1 contains a subset of the values listed in names:

Name    Count
name_1  14
name_3  2
name_5  11

我想使用名称向量为数据框中当前缺少的名称向数据框中添加行,以便最终产品如下所示:

I would like to use the vector of names to add rows to the data frame for names that are currently missing from the data frame, so that the final product looks like this:

Name    Count
name_1  14
name_2  0
name_3  2
name_4  0
name_5  11

我遇到了这个问题的其他一些变体,但似乎无法找到与我的场景相匹配的解决方案.感谢您的帮助!

I've come across some other variations of this question, but can't seem to find a solution that matches my scenario. Thanks for any help!

推荐答案

一个选项是 complete

library(tidyr)
complete(df1, Name = names, fill = list(Count = 0))
# A tibble: 5 x 2
#  Name   Count
#  <chr>  <dbl>
#1 name_1    14
#2 name_2     0
#3 name_3     2
#4 name_4     0
#5 name_5    11

数据

df1 <- structure(list(Name = c("name_1", "name_3", "name_5"), Count = c(14L, 
2L, 11L)), class = "data.frame", row.names = c(NA, -3L))

这篇关于使用向量中的值在数据框中添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆