简体   繁体   English

在 R - 如果单元格值与列匹配,则返回值,否则在新的 dataframe 中为 0

[英]In R - if cell value matches a column, return value, else 0 in a new dataframe


B1  B2  total
10  0   10
20  20  40
0   20  20
10  20  30

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 cell value, else 0.按行排列,如果单元格 (B1:B2) 与 d$total 匹配,则返回单元格值,否则为 0。

To look like this看起来像这样

B1   B2
10   0
0    0
0    20
0    0

What is the best way to do this in R?在 R 中执行此操作的最佳方法是什么?

Thank you.谢谢你。

You can turn the values to 0 where total does not match values in first two columns.您可以将值设置为 0,其中total与前两列中的值不匹配。

df1 <- df[1:2]
df1[df1 != df$total] <- 0
df1

#  B1 B2
#1 10  0
#2  0  0
#3  0 20
#4  0  0

Here's a tidyverse way:这是一个tidyverse的方式:

library(tidyverse)

df <- tribble(
  ~ B1, ~ B2, ~ total,
  10,  0,   10,
  20,  20,  40,
  0,   20,  20,
  10,  20,  30
)

df %>%
  mutate(
    B1 = if_else(B1 == total, B1, 0),
    B2 = if_else(B2 == total, B2, 0)
  ) %>%
  select(B1, B2)
#> # A tibble: 4 x 2
#>      B1    B2
#>   <dbl> <dbl>
#> 1    10     0
#> 2     0     0
#> 3     0    20
#> 4     0     0

Created on 2020-11-25 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 11 月 25 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R - 在新的 dataframe 中:如果单元格匹配同一行的另一列,则 - R - In new dataframe: if cell matches another column of same row, then 返回单元格值与模式匹配的 R 数据框的行和列位置 - Return the row and column position of R data frame where the cell value matches a pattern 如果一个值然后在 R 的新列中返回另一个值 - If a value then return another value in a new column in R 如果单个单元格值与R中的辅助列匹配,则指定单个单元格值 - Designating single cell value if it matches any in secondary column in R 基于其他值列的新列值数据框的R公式 - R formula for new column value dataframe based on other value column 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 在 R 中,我的 dataframe 的一列填充了其他数据帧。 我想在原始 dataframe 中将特定值作为新列返回 - In R, a column of my dataframe is populated with other dataframes. I want to return a specific value as a new column in the original dataframe R使用if else逻辑将值分配给新列 - R use if else logic to assign value to new column 在 R 中使用 if {} else {} 在数据框中创建新列 - Create new column in dataframe using if {} else {} in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM