基于多列重新编码数据帧列 [英] Recoding data frame column based on multiple columns
本文介绍了基于多列重新编码数据帧列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据其他列的值重新编列列?说我有下面的数据框,我想重新编码 df $ Col3
,以便如果 df $ Col1 == x
和 df $ Col2 == a
。
How do I recode a column based on values from other columns? Say I have the below data frame and I want to recode df$Col3
so that the value is 0 if df$Col1 == x
and df$Col2 == a
.
> df <- data.frame(a=c(rep("x",3),rep("y",3),rep("x",4)),letters[c(1:5,3,4:1)],1:10)
> names(df)<-c("Col1","Col2","Col3")
> df
Col1 Col2 Col3
1 x a 1
2 x b 2
3 x c 3
4 y d 4
5 y e 5
6 y c 6
7 x d 7
8 x c 8
9 x b 9
10 x a 10
推荐答案
您可以使用 ifelse
> df$Col3 <- with(df, ifelse(Col1=='x' & Col2=='a', 0, Col3))
> df
Col1 Col2 Col3
1 x a 0
2 x b 2
3 x c 3
4 y d 4
5 y e 5
6 y c 6
7 x d 7
8 x c 8
9 x b 9
10 x a 0
这篇关于基于多列重新编码数据帧列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文