r - Comparing Dataframe column names in R
问题描述
I am trying to compare the column names between two dataframes and modify the columns in the latter dataframe.
n = c(0, 1, 0)
s = c(1, 0, 1)
b = c(1, 1, 1)
a = c(0, 0, 0)
c = c(1,3,2)
df1 = data.frame(n, s, b)
df2 = data.frame(n,s,a,c)
How do I write a syntax comparing/merging df1 and df2 such that the outputs are as follows:
df1 output:
n s b
1 0 1 1
2 1 0 1
3 0 1 1
df2 output:
n s b
1 0 1 0
2 1 0 0
3 0 1 0
Any help is appreciated thank you!
解决方案
我们可以使用intersect
和setdiff
#Drop columns from df2 which are not present in df1
df2 <- df2[intersect(names(df1), names(df2))]
#add columns which are present in df1 but not in df2 and assign it to 0
df2[setdiff(names(df1), names(df2))] <- 0
df2
# n s b
#1 0 1 0
#2 1 0 0
#3 0 1 0
推荐阅读
- javascript - 在数组中查找对象时,Typescript 对象可能未定义
- statistics - 是否有对 2 个变量进行排序的命令?
- ios - 使用 UIPageViewController 为部分翻页设置动画
- webrtc - WebRTC:事件“ontrack”不会触发
- python - 如何在 MacBook Air M1 上安装 python 和工作 ide
- python - dash 和另一个线程之间使用队列进行通信
- java - 使用 JSoup 从网站收集列表条目时被抛出我的 for 循环
- javascript - 使用材质 UI 时出现的 Grid 问题
- prestashop-1.7 - 如何在 Prestashop 中将添加到购物车替换为缺货
- reactjs - (react-csv) 分配具有相同列名但来自不同表的 csv 标题