[英]starting column row values based on previous column value - R
I have a dataframe as follows:我有一个 dataframe 如下:
xR <- data.frame("A" = c(15, 13.5, 12, 9.1, NA, NA, NA, NA),
"B" = c(NA, 13.6, 8.4, 6.7, 5.6, 2.0, NA, NA),
"C" = c(NA, NA, 8.5, 2.43, 1.23, NA, NA, NA))
Is it possible to shift values in Col B so that it starts on same row of Col A where first value of Col B is lower than corresponding row value in Col A. Shift values in Col C so that it starts on same row of Col B where first value of Col C is lower than corresponding row value in Col B and so on for each of the columns in my dataframe. My dataframe has many more columns than this so need to try automate it.是否可以移动 Col B 中的值,使其从 Col A 的同一行开始,其中 Col B 的第一个值低于 Col A 中的相应行值。移动 Col C 中的值,使其从 Col B 的同一行开始其中 Col C 的第一个值低于 Col B 中相应的行值,依此类推我的 dataframe 中的每一列。我的 dataframe 的列比这多得多,因此需要尝试使其自动化。
I'm hoping to end up with the following:我希望最终得到以下结果:
xR1 <- data.frame("A" = c(15, 13.5, 12, 9.1, NA, NA, NA, NA),
"B" = c(13.6, 8.4, 6.7, 5.6, 2.0, NA, NA, NA),
"C" = c(NA, 8.5, 2.43, 1.23, NA,NA, NA, NA))
Thanks谢谢
Here is one approach.这是一种方法。 In each column:
在每一列中:
First, identify the first non-NA position.首先,确定第一个非 NA position。
Second, determine the new position to shift the first non-NA position to.其次,确定新的 position 以将第一个非 NA position 转移到。 This will be the minimum where the value of the first non-NA position is less than the value in the previous column.
这将是第一个非 NA position 的值小于上一列中的值的最小值。
Third, shift the vector of that column by the difference between the new position and first non-NA position.第三,将该列的向量移动新的 position 和第一个非 NA position 之间的差异。
for (i in 2:ncol(xR)) {
first_non_NA_position <- which.min(is.na(xR[[i]]))
new_position <- min(which(xR[[i]][first_non_NA_position] < xR[[i-1]]))
position_diff <- first_non_NA_position - new_position
if (position_diff > 0) {
xR[[i]] <- c(tail(xR[[i]], -position_diff), rep(NA, position_diff))
}
}
Output Output
A B C
1 15.0 13.6 8.50
2 13.5 8.4 2.43
3 12.0 6.7 1.23
4 9.1 5.6 NA
5 NA 2.0 NA
6 NA NA NA
7 NA NA NA
8 NA NA NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.