如何从列表中向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 2How 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 0I 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 0I'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))] <- 0We can get the column names that are not in 'df1' using setdiff and assign those to 0
df1[setdiff(names(df2), names(df1))] <- 0更多推荐
发布评论