创建一个新变量,基于两列的值和一个向量中的值。

huangapple go评论50阅读模式
英文:

Create a new variable based on values in two columns and list of values in a vector

问题

我有一个包含列"V1"和"V2"的数据框。

Z <- c('931', '907', '905', '902', '8552', '855', '8542', '854', '8532', '853', '852', '851', '850')

我想要在数据框中添加一个新变量"Match",如果满足以下条件,则"Match"取值为1、2或3:

"Match=1",如果"V1"和"V2"中的值相同

"Match=2",如果"V1"和"V2"中的值都包含在向量"Z"中的任何值中

"Match=3",如果"V1"或"V2"中的值包含在向量"Z"中的值之外的任何值

最终的数据框应该具有如下所示的"Match"列中的值:

V1 V2 Match
8552 689 3
576 8552 3
8552 907 2
8552 85 3
8552 902 2
8552 783 3
931 367 3
8552 1090 3
8552 905 2
8552 8552 1
8552 1004 3
113 907 3
8552 1001 3
8542 564 3
850 720 3

英文:

I have a dataframe with columns "V1" and "V2".

Z&lt;- c(&#39;931&#39;, &#39;907&#39;,&#39;905&#39;,&#39;902&#39;,&#39;8552&#39;,&#39;855&#39;,&#39;8542&#39;,&#39;854&#39;,&#39;8532&#39;,&#39;853&#39;,&#39;852&#39;,&#39;851&#39;,&#39;850&#39;)

I want to add a new variable "Match" to the dataframe which takes the values 1, 2, or 3 if the following conditions satisfies:

Match=1, if value in V1 and V2 are same

Match=2, if value in both V1 and V2 contain any of the values in vector Z

Match=3, if value in V1 or V2 contain any values other than the values in vector Z

The resulting dataframe should have the values as given in column Match.

V1	    V2	    Match
8552	689	    3
576		8552    3
8552	907	    2
8552	85	    3
8552	902	    2
8552	783	    3
931 	367	    3
8552	1090	3
8552	905	    2
8552	8552	1
8552	1004	3
113 	907	    3
8552	1001	3
8542	564	    3
850 	720	    3

答案1

得分: 0

你可以使用 {dplyr} 包中的 case_when 语句,就像这样:

df %>% mutate(Match = case_when(V1 == V2 ~ 1,
                                V1 %in% Z & V2 %in% Z ~ 2,
                                !(V1 %in% Z) | !(V2 %in% Z) ~ 3)

请注意,这是代码部分,不需要翻译。

英文:

you can use a case_when statement from the {dplyr} package. like so:

df %&gt;% mutate(Match = case_when(V1 == V2 ~ 1,
                                V1 %in% Z &amp; V2 %in% Z ~ 2,
                                !(V1 %in% Z) | !(V2 %in% Z) ~ 3)

huangapple
  • 本文由 发表于 2023年6月15日 04:21:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定