gpt4 book ai didi

r - 有条件地替换 R 中的值

转载 作者:行者123 更新时间:2023-12-05 08:47:40 24 4
gpt4 key购买 nike

我有一个关于 R 的问题。我有一个数据集,我想根据彼此相邻的列的值更改其单元格

Data <- tibble(a = 1:5,  
b = c("G","H","I","J","K"),
c = c("G","H","J","I","J"))

我想更改字符。如果 b 和 c 具有相同的字符,则为 NA。

期望的输出

Data <- tibble(a = 1:5,  
b = c("NA","NA","I","J","K"),
c = c("NA","NA","J","I","J"))

非常感谢您的提前帮助。

最佳答案

library(data.table)
setDT(Data)[b == c, c("b", "c") := NA]
# a b c
# 1: 1 <NA> <NA>
# 2: 2 <NA> <NA>
# 3: 3 I J
# 4: 4 J I
# 5: 5 K J

关于r - 有条件地替换 R 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67108357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com