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