[英]R - In new dataframe: if cell matches another column of same row, then
d <- data.frame(B1 = c(1,2,3,4),B2 = c(0,1,2,3))
d$total=rowSums(d)
B1 B2 total
1 0 1
2 1 3
3 2 5
4 3 7
Using the dataframe above, I want to create a new dataframe with the following logic:使用上面的 dataframe,我想用以下逻辑创建一个新的 dataframe:
Going by rows, if cells (B1:B2) matches d$total, return 1, else 0.按行计算,如果单元格 (B1:B2) 与 d$total 匹配,则返回 1,否则返回 0。
Ideally output to look like:理想情况下 output 看起来像:
B1n B2n
1 0
0 0
0 0
0 0
What is the best way to do this in R?在 R 中执行此操作的最佳方法是什么?
Thank you.谢谢你。
You can compare first 2 columns with total
value.您可以将前 2 列与total
进行比较。
res <- +(d[1:2] == d$total)
res
# B1 B2
#[1,] 1 0
#[2,] 0 0
#[3,] 0 0
#[4,] 0 0
The result is a matrix, if you want dataframe as output you can do res <- data.frame(res)
.结果是一个矩阵,如果你想要 dataframe 作为 output 你可以做res <- data.frame(res)
。
Here is an alternate way to solve this problem.这是解决此问题的另一种方法。 You can use dplyr::transmute which is the opposite of dplyr::mutate which will give you two separate columns.您可以使用 dplyr::transmute 与 dplyr::mutate 相反,它将为您提供两个单独的列。 Inside transmute are just conditions.内部转化只是条件。
library(dplyr)
newdf <- d %>% transmute(B1n=ifelse(B1+B2==B1,1,0),B2n=ifelse(B1+B2==B2,1,0))
> newdf
B1n B2n
1 1 0
2 0 0
3 0 0
4 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.