r - 如何根据条件在 R 中上下移动整行?

标签 r dataframe dplyr

假设我有一些看起来像这样的数据

Name     Type   Rating

Dave     Good   3.0
Steve    Bad    0.0
Steve    Good   2.0
Dave     Bad    1.0
Tom      Bad    2.0
Marianne Good   0.0
Tom      Bad    1.0
Steve    Bad    5.5
Marianne Bad    3.0

我想获取满足条件“type=='good''和'Rating==2.0'的任何行,并将整行向上或向下移动 1 行。我将如何在 R 中执行此操作?

所以它看起来像这样。

Name     Type   Rating

Dave     Good   3.0
Steve    Good   2.0
Steve    Bad    0.0
Dave     Bad    1.0
Tom      Bad    2.0
Marianne Good   0.0
Tom      Bad    1.0
Steve    Bad    5.5
Marianne Bad    3.0

最佳答案

这是否能满足您的需求?我使用了一个稍微编辑过的 data.frame 来展示它如何处理边缘情况(即你想向下移动,但你已经在最后一行)。

rows <- rep(which(df$Type == "Good" & df$Rating == 2.0), each = 2)
all_rows <- 1:nrow(df)
#For moving DOWN change "-" to "+"
all_rows[replace(rows - c(1,0), rows - c(1,0) > nrow(df) | rows - c(1,0) < 1, NA) %>% na.omit] <- replace(rows - c(0,1), rows - c(0,1) > nrow(df) | rows - c(0,1) < 1, NA) %>% na.omit
df[all_rows,]



#          Name Type Rating
#1      Mike Good    2.0
#2      Dave Good    3.0
#4     Steve Good    2.0
#3     Steve  Bad    0.0
#5      Dave  Bad    1.0
#6       Tom  Bad    2.0
#7  Marianne Good    0.0
#8       Tom  Bad    1.0
#9     Steve  Bad    5.5
#11    Steve Good    2.0
#10 Marianne  Bad    3.0

数据:

df <- read.table(text="Name     Type   Rating
Mike     Good   2.0
Dave     Good   3.0
Steve    Bad    0.0
Steve    Good   2.0
Dave     Bad    1.0
Tom      Bad    2.0
Marianne Good   0.0
Tom      Bad    1.0
Steve    Bad    5.5
Marianne Bad    3.0
Steve    Good   2.0", header = T)

关于r - 如何根据条件在 R 中上下移动整行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49089936/

相关文章:

r - 使用 dplyr 按特定值划分列

r - 如何更优雅地操作不同列表中的data.frame对象?

r - 如何在没有 `dplyr` 的情况下将数据附加到 `collect()` 的 PostgreSQL 表?

r - 熔化和 reshape 具有相似列根词的列

r - dplyr 创建因子水平的聚合百分比

从因子变量中删除特定因子水平

r - 在 Shiny 应用程序中对齐多列中的复选框元素

r - Purrr 根据包含字符向量的非嵌套变量过滤嵌套数据

list - 如何从 Pandas 数据框中制作列表列表,跳过 nan 值

python - 如何将 timedelta 转换为小时