如何从列表中向R dataframe添加多个列(How to add multiple columns to R dataframe from list)

编程入门 行业动态 更新时间:2024-10-25 16:16:50
如何从列表中向R dataframe添加多个列(How to add multiple columns to R dataframe from list)

我有一个数据帧:

df1 a b c 1 1 0 1 1 1 1 1 1 df2 a b c d e f 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2

如何从df2向df1添加不在df1新列? 要得到:

df2 a b c d e f 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0

我试过了:

columns_toadd <- colnames(df1)[!(colnames(df1) %in% colnames(df2))] for (i in 1:length(columns_toadd)){ df$columns_toadd[[i]] <- 0 }

但这只是给了:

df2 a b c columns_toadd 1 1 0 0 1 1 1 0 1 1 1 0

我想在基础R中这样做,因为我在有限包的环境中工作。

I have a dataframe:

df1 a b c 1 1 0 1 1 1 1 1 1 df2 a b c d e f 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2

How can I add new columns to df1 from df2 that aren't in df1? to get:

df2 a b c d e f 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0

I tried:

columns_toadd <- colnames(df1)[!(colnames(df1) %in% colnames(df2))] for (i in 1:length(columns_toadd)){ df$columns_toadd[[i]] <- 0 }

But this just gave:

df2 a b c columns_toadd 1 1 0 0 1 1 1 0 1 1 1 0

I'd like to do this in base R as I work in an environment with limited packages.

最满意答案

我们可以使用setdiff获取不在'df1'中的列名,并将它们分配给0

df1[setdiff(names(df2), names(df1))] <- 0

We can get the column names that are not in 'df1' using setdiff and assign those to 0

df1[setdiff(names(df2), names(df1))] <- 0

更多推荐

本文发布于:2023-08-06 20:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   中向   列表   columns   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!