简体   繁体   English

将列值与另一列进行比较

[英]Compare column values against another column

I have the following data: 我有以下数据:

set.seed(1)

data <- data.frame(
id = 1:500, ht_1 = rnorm(500,10:20), ht_2 = rnorm(500,15:25),
ht_3 = rnorm(500,20:30), ht_4 = rnorm(500,25:35), 
ht_5 = rnorm(500,20:40)
)

I would like to identify the values in columns ht_1:ht_4 that are greater than the values in column ht_5 (number of observations and means). 我想,以确定列中的值ht_1:ht_4是比在列中的值更大ht_5 (观察和装置的数量)。

For each of these columns, I would then like to replace any values that are greater than ht_5 with ht_5 . 对于这些列中的每一列,我ht_5ht_5替换任何大于ht_5ht_5

Hi you can use the mutate_at function like this: 嗨,您可以像这样使用mutate_at函数:

library(tidyverse)

data %>% as_tibble %>% 
  mutate_at(vars(paste0("ht_", 1:4)), ~if_else(.x > ht_5, ht_5, .x))

In this case you can also use pmin instead of if_else which should be faster. 在这种情况下,您也可以使用pmin代替if_else ,它应该更快。

data %>% as_tibble %>% 
      mutate_at(vars(paste0("ht_", 1:4)), ~pmin(.x, ht_5))

To see how many values are greater than ht_5 you can use the summarise_at function: 看看有多少值都大于ht_5可以使用summarise_at功能:

data %>% as_tibble %>% 
  summarize_at(vars(paste0("ht_", 1:4)), ~ length(.x[.x > ht_5]))

# A tibble: 1 x 4
   ht_1  ht_2  ht_3  ht_4
  <int> <int> <int> <int>
1     6    39   131   258

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将列值与第一行进行比较,并保留R中的原始值 - Compare column values against first row and retain original values in R 将一个矩阵的几列与R中另一矩阵的列进行比较 - Compare a few columns of one matrix against the column of another matrix in R 如何在与另一列对照时更改一列中的值? - How to change values in a column while checking them against another column? 将列中的值与R中的组中的多个值进行比较 - compare values of a column with multiple values in another column by group in R 将一列中的值与 R 中的另一列中的值进行比较 - Compare values in one column to another in R 是否有 R 函数来比较 1 列值与另一列的所有值? - Is there an R function to compare between 1 column value with all values of another column? 使用 if 比较列值 - Using if to compare column values 将一列的框 plot 与另一列的值显示为 x 轴 - Show box plot of one column against values from another column as x axis 对照另一列检查一个数据框列中的值或模式以查看是否出现匹配项 - Check values or pattern in one dataframe column against another column to see if match appears 如何根据R中另一列的值总和绘制一列的因子? - How to plot factors of one column against their total sum of values from another column in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM