我在 R 中使用了一个数据框,其中 col4 应该小于 col5,但有时这种情况不会发生。
无论如何我可以将值从 col4 转移到 col5,反之亦然,而不必使用 forloop,因为它们在 R 中相当耗时。
即,如果对于给定的行 col4 = 100,col5=10,我想移动它们,col4 应该变成 10,col5 应该变成 100。
欢迎指教,先谢谢了!
假设您的数据框名为 d:
newCol4 <- pmin(d$col4, d$col5)
newCol5 <- pmax(d$col4, d$col5)
d$col4 <- newCol4
d$col5 <- newCol5
您可以使用逻辑索引,也可以使用临时变量来进行交换?
# 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
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 循环。