有条件的更新值(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 DI 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 Avectors a and b could have any length BUT need to be paired with value x and value y.
更多推荐
XYZ,电脑培训,计算机培训,IT培训"/> <meta name="description" content
发布评论