r - Is there an R function to combine multiple columns from the same data frame into the same column?
问题描述
At the moment I have four columns that need to be combined/merged into one column. Each row will either have four "0"s OR there will be one "1" with three "0"s.
This is what the data frame looks like right now:
id L1_Correct L2_Correct L3_Correct L4_Correct
1 0 0 0 1
2 1 0 0 0
3 0 1 0 0
4 1 0 0 0
5 0 0 1 0
This is what I want the dataframe to look like:
id L1_Correct L2_Correct L3_Correct L4_Correct Combined__L_Accuracy
1 0 0 0 1 1
2 1 0 0 0 1
3 0 0 0 0 0
4 1 0 0 0 1
5 0 0 0 0 0
I tried using the paste function and the unite function on separate occasions: I.e,
L_Data$Combine_L_Accuracy <- paste(L_Data$L1_Correct, L_Data$L2_Correct, L_Data$L3_Correct, L_Data$L4_Correct)
L_Data_all <- L_Data %>% unite(Combine_L_Accuracy, L1_Correct, L2_Correct, L3_Correct, L4_Correct, na.rm = TRUE, remove = TRUE)
L_Data_all
But they both provided me with an outcome like: 0_0_0_0 I only need 1 value in the last column either a 0 or 1 based on values across the four columns.
解决方案
You can use rowSums
to sum all the "Correct"
columns :
cols <- grep('Correct', names(L_Data))
L_Data$Combined_L_Accuracy <- rowSums(L_Data[cols])
推荐阅读
- node.js - 从 index.ts 导入页面组件和 getServerSideProps
- php - 缩放到 MOZILLA 中嵌入的 PDF 绘图中的文本
- c# - 领域事件调用存储库是否可以接受?或者执行子任务的其他选项是什么?
- javascript - 多个按钮上的事件监听器
- vba - MS Word VBA将文本框附加到偶数和奇数标题
- python - 通过 Jquery 使用 django-filter 和 django-tables2 管理所有字段的单个搜索栏
- c++ - C++ QT tableView在设置自定义标题后不显示标题标签
- google-chrome - 无法在 Chrome 浏览器中的 Apache JMeter 中记录
- javascript - 如何在 nuxt SSR 中设置 plotly.js?
- angular - Angular:使用 NgIf 进行更改检测问题