如何在两列之间交换值 [英] How to swap values between two columns
本文介绍了如何在两列之间交换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含三个变量和250K记录的数据框。例如
I have a data frame with three variables and 250K records. As an example consider
df <- data.frame(V1=c(1,2,4), V2=c("a","a","b"), V3=c(2,3,1))
V1 V2 V3
1 a 2
2 a 3
4 b 1
,并希望基于V2的值在V1和V3之间交换值,如下所示:
如果 V2 =='b'
,则 V1 <-V3
和 V3<-V1
导致
and want to swap values between V1 and V3 based on the value of V2 as follows:
if V2 == 'b'
then V1 <- V3
and V3 <- V1
resulting in
V1 V2 V3
1 a 2
2 a 3
1 b 4
我尝试了do循环但这需要永远。如果我使用Perl,则需要几秒钟。我相信在R中也可以有效地完成此任务。谢谢您的任何建议。
I tried a do loop but it takes forever. If I use Perl, it takes seconds. I believe this task can be done efficiently in R as well. Any suggestions are appreciated.
推荐答案
尝试一下
df <- data.frame(V1=c(1,2,4), V2=c("a","a","b"), V3=c(2,3,1))
df[df$V2 == "b", c("V1", "V3")] <- df[df$V2 == "b", c("V3", "V1")]
其结果是:
> df
V1 V2 V3
1 1 a 2
2 2 a 3
3 1 b 4
这篇关于如何在两列之间交换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文