用另一个字符串有条件地替换字符串 [英] Conditional replacement of string with another string
本文介绍了用另一个字符串有条件地替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据结构,所有变量都是字符串格式:
I have the following structure of the data with all variables being in the string format:
v1 v2 c1 c2 c1c2
00035A 943567 00088E 63968E 00088E;63968E
00088E 63968E 00088E 63968E 00088E;63968E
00088E 925524 00088E 63968E 00088E;63968E
000361 237924 00088E 63968E 00088E;63968E
000361 83367A 00088E 63968E 00088E;63968E
00055X 49328R 00088E 63968E 00088E;63968E
00056N 87885Q 00088E 63968E 00088E;63968E
000794 69911G 00088E 63968E 00088E;63968E
23792A 001674 00088E 63968E 00088E;63968E
63968E 17275R 00088E 63968E 00088E;63968E
如果 v1=c1
和 v2<,我想做的是用
c1c2
替换 v1
的值/code> with c1c2
if v2=c2
通过使用 R 中的一些通用命令,即不包含 c1
的特定值,c2
和 c1c2
.
What I'd like to do is to replace the value of v1
with c1c2
if v1=c1
and v2
with c1c2
if v2=c2
by using some general command in R, i.e. which does not contain specific values of c1
, c2
, and c1c2
.
非常感谢您的帮助.
推荐答案
有几种方法可以做到这一点:
There are several ways in which you can do this:
1:在基 R 中使用 ifelse
语句:
1: with ifelse
statements in base R:
df$v1 <- ifelse(df$v1==df$c1, df$c1c2, df$v1)
df$v2 <- ifelse(df$v2==df$c2, df$c1c2, df$v2)
2:或带有子集分配:
df[df$v1==df$c1,"v1"] <- df[df$v1==df$c1,"c1c2"]
df[df$v2==df$c2,"v2"] <- df[df$v2==df$c2,"c1c2"]
3:或使用 data.table 包:
library(data.table)
setDT(df)[v1==c1, v1 := c1c2][v2==c2, v2 := c1c2]
这些解决方案中的每一个都给出了以下结果:
each of these solutions gives the following result:
> df
v1 v2 c1 c2 c1c2
1: 00035A 943567 00088E 63968E 00088E;63968E
2: 00088E;63968E 00088E;63968E 00088E 63968E 00088E;63968E
3: 00088E;63968E 925524 00088E 63968E 00088E;63968E
4: 000361 237924 00088E 63968E 00088E;63968E
5: 000361 83367A 00088E 63968E 00088E;63968E
6: 00055X 49328R 00088E 63968E 00088E;63968E
7: 00056N 87885Q 00088E 63968E 00088E;63968E
8: 000794 69911G 00088E 63968E 00088E;63968E
9: 23792A 001674 00088E 63968E 00088E;63968E
10: 63968E 17275R 00088E 63968E 00088E;63968E
这篇关于用另一个字符串有条件地替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文