有条件的更新值(Conditional update value)

编程入门 行业动态 更新时间:2024-10-11 15:14:16
有条件的更新值(Conditional update value)

我在R中有一个名为dfData的数据框,如下所示;

x y 10 A 20 B 30 C 40 D

我正在努力实现以下目标;

如果X中的值为10,则将该值更新为“XYZ”

有没有一个功能或优雅的方式来做到这一点在R? 试图避免多个ifelse语句。

谢谢

I have a dataframe called dfData in R as below;

x y 10 A 20 B 30 C 40 D

I am trying to achieve the following;

if the value in X is 10, update the value to "XYZ"

Is there a function or elegant way to do this in R? Trying to avoid multiple ifelse statements.

Thanks

最满意答案

如果您需要根据x值来替换许多y值,则一种可行的方法是:

# define df as data.table library(data.table) df <- data.table(x=c(10,20,30,40,50,60,70,80,90), y= c('A', 'B', 'C', 'D','A', 'B', 'C', 'D', 'A')) > df x y 1: 10 A 2: 20 B 3: 30 C 4: 40 D 5: 50 A 6: 60 B 7: 70 C 8: 80 D 9: 90 A # define your pair of values for replacement a <- c(10,20,50) b <- c('XYZ', 'ZYX', 'AAA') # x = 10 will cause y to be replaced by 'XYZ', x= 20 will cause y to be replaced by 'ZYX' and so on ... # replacement for (i in 1:length(a)) { df[ x==a[i], y := b[i]] } > df x y 1: 10 XYZ 2: 20 ZYX 3: 30 C 4: 40 D 5: 50 AAA 6: 60 B 7: 70 C 8: 80 D 9: 90 A

向量a和b可以有任何长度,但需要与值x和值y配对。

If you need to replace many y values depending on x values, one posible approach is:

# define df as data.table library(data.table) df <- data.table(x=c(10,20,30,40,50,60,70,80,90), y= c('A', 'B', 'C', 'D','A', 'B', 'C', 'D', 'A')) > df x y 1: 10 A 2: 20 B 3: 30 C 4: 40 D 5: 50 A 6: 60 B 7: 70 C 8: 80 D 9: 90 A # define your pair of values for replacement a <- c(10,20,50) b <- c('XYZ', 'ZYX', 'AAA') # x = 10 will cause y to be replaced by 'XYZ', x= 20 will cause y to be replaced by 'ZYX' and so on ... # replacement for (i in 1:length(a)) { df[ x==a[i], y := b[i]] } > df x y 1: 10 XYZ 2: 20 ZYX 3: 30 C 4: 40 D 5: 50 AAA 6: 60 B 7: 70 C 8: 80 D 9: 90 A

vectors a and b could have any length BUT need to be paired with value x and value y.

更多推荐

XYZ,电脑培训,计算机培训,IT培训"/> <meta name="description" content

本文发布于:2023-07-19 04:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1173702.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   Conditional   update

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!