2012-11-20 36 views
1

我在R中使用了一個數據幀,其中col4應該小於col5,但有時候並不會發生。數據幀移位列

反正是有,我可以將值從COL4轉向COL5,反之亦然,而無需使用一個for循環,因爲他們是有相當時間R.

昂貴

也就是說,如果對於一個給定的行COL4 = 100,和col5 = 10,我想轉移它們,col4應該變爲10,並且col5應該變爲100.

提醒歡迎,提前致謝!

回答

4

假設你的數據幀被命名爲d:

newCol4 <- pmin(d$col4, d$col5) 
newCol5 <- pmax(d$col4, d$col5) 

d$col4 <- newCol4 
d$col5 <- newCol5 
2

你可以使用邏輯索引和可能是一個臨時變量做交換?

# find the rows where col4 >= col5 (or maybe >? depends on what you want) 
idx <- data$col4 >= data$col5 
# idx is TRUE for columns we want to swap. 

# now do the swap: 
# a) save data$col5 
tmp <- data$col5[idx] 
# b) replace data$col5 with the col4 values (where relevant) 
data$col5[idx] <- data$col4[idx] 
# c) replace data$col4 with our saved col5 values 
data$col4[idx] <- tmp 
+0

對於給定的例子,>將給出> =相同的結果。當然可能有更高的目的。 –

+0

是的,這就是我提到它的原因。 –

1
indices <- which(data.frame.instance[,4]<data.frame.instance[,5]) 
data.frame.copy <- data.frame.instance 
data.frame.copy[indices,5] <- data.frame.instance[indices,4] 
data.frame.instance[indices,5] <- data.frame.copy[indices,4] 
rm(data.frame.copy, indices) 

應該做你想要什麼 - 沒有for循環。

+0

對'哪個'的調用不是必需的,可以刪除。 –