检查是否存在列,如果不添加

发布于 2025-02-12 08:22:15 字数 112 浏览 1 评论 0原文

我有一系列非耗尽的数据范围。在清洁过程中,我想循环浏览数据框架,并检查某些列是否存在以及是否不存在它们。我一生都无法找到一种方法来做到这一点。我不害羞,更喜欢它们而不是基础。

任何方向都非常感谢。

I have a series of dataframes that are noncumulative. During the cleaning process I want to loop through the dataframe and check if certain columns exists and if they aren't present create them. I can't for the life of me figure out a method to do this. I am not package shy and prefer them to base.

Any direction is much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑凤梨 2025-02-19 08:22:15

您可以使用此虚拟数据dfcoltoadd列以检查是否不存在添加

df <- data.frame(A = rnorm(5) , B = rnorm(5) , C = rnorm(5))

colToAdd <- c("B" , "D")

,然后应用该列是否存在null产生的您的列Eg rnorm(5)

add <- sapply(colToAdd , \(x) if(!(x %in% colnames(df))) rnorm(5))

data.frame(do.call(cbind , c(df , add)))

  • 输出
           A          B          C          D
1  1.5681665 -0.1767517  0.6658019 -0.8477818
2 -0.5814281 -1.0720196  0.5343765 -0.8259426
3 -0.5649507 -1.1552189 -0.8525945  1.0447395
4  1.2024881 -0.6584889 -0.1551638  0.5726059
5  0.7927576  0.5340098 -0.5139548 -0.7805733

You can use this dummy data df and colToAdd columns to check if not exists to add

df <- data.frame(A = rnorm(5) , B = rnorm(5) , C = rnorm(5))

colToAdd <- c("B" , "D")

then apply the check if the column exists NULL produced else add your column e.g. rnorm(5)

add <- sapply(colToAdd , \(x) if(!(x %in% colnames(df))) rnorm(5))

data.frame(do.call(cbind , c(df , add)))

  • output
           A          B          C          D
1  1.5681665 -0.1767517  0.6658019 -0.8477818
2 -0.5814281 -1.0720196  0.5343765 -0.8259426
3 -0.5649507 -1.1552189 -0.8525945  1.0447395
4  1.2024881 -0.6584889 -0.1551638  0.5726059
5  0.7927576  0.5340098 -0.5139548 -0.7805733
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文