简体   繁体   English

R - 在新的 dataframe 中:如果单元格匹配同一行的另一列,则

[英]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.

相关问题 在 R - 如果单元格值与列匹配,则返回值,否则在新的 dataframe 中为 0 - In R - if cell value matches a column, return value, else 0 in a new dataframe 根据R中同一行的另一列中的单元格的值对一列求和 - Sum a column based on the value of a cell in another column of the same row in R R将函数应用于数据框的每一行,将结果存储在同一数据框的新列中 - R apply function to each row of dataframe, store result in new column of same dataframe 在 R dataframe 中使用行总和创建一个新列 - Create a new column in R dataframe with row sum 根据该行中另一个单元格的值更改 dataframe 单元格中的值 (R) - Changing a value in a dataframe cell based on the value of another cell in that row (R) 新的数据框合并另一个列的总和,R - New dataframe cointaning sum of column of another, R R:使用另一个数据框创建一个新列 - R: Creating a new column using another dataframe R - 如果列名与字符串匹配,则将值添加到新行 - R - adding a value to a new row if column name matches a string 如果列的第二行与 r 中的值匹配,则创建新变量 - Create new variable if second row of a column matches a value in r dataframe 的搜索列,每个 i 在同一 dataframe 的另一列中 - R - Search column of a dataframe with each i in another column of the same dataframe - R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM