r - 如何用单个值替换数据框中每行的最大值

标签 r dataframe replace

今天我未能完成一项简单的任务:

我想用我之前计算过的特定单个值替换数据帧每行中的最大值。我不知道我怎么知道

DF <- structure(list(age_n = c(2, 3, 3, 3, 3, 3), female_noe_n = c(0.674555812063115, 
0.681331945419623, 0.632659475334461, 0.649517172953091, 0.64918662986253, 
0.667531771388686), male_noe_n = c(0.734797290317925, 0.742565052946117, 
0.715791062610646, 0.729425965096302, 0.710171830071103, 0.734962561863205
), female_v_n = c(0.745209397670608, 0.86387436718214, 0.915191181991792, 
1.01146185711779, 1.04658206048994, 1.11211222819373), male_v_n = c(0.783635031948367, 
0.860486300503885, 0.909571949452249, 0.995595788770845, 1.03071599214299, 
1.12996155508404)), row.names = c(NA, 6L), class = "data.frame")

ID <- apply(DF, 1, function(x) which.max(x))

# Now I need to overwrite the rowwise maximum by ceiling 
overwrite_value <- 
  sapply(1:nrow(DF), function(x)
    DF[x,ID[[x]]] %>% ceiling())

我想有简单的解决方案,但我陷入了过于复杂的问题

最佳答案

这是一个 dplyr 解决方案:

library(dplyr)

individual_value <- 5

DF %>% 
  rowwise() %>% 
  mutate( x = max(c_across(2:5))) %>% 
  mutate(across(2:5, ~case_when(. == x ~ individual_value,
                                TRUE ~ .)), .keep="unused"
         )
  age_n female_noe_n male_noe_n female_v_n male_v_n
  <dbl>        <dbl>      <dbl>      <dbl>    <dbl>
1     2        0.675      0.735      0.745    5    
2     3        0.681      0.743      5        0.860
3     3        0.633      0.716      5        0.910
4     3        0.650      0.729      5        0.996
5     3        0.649      0.710      5        1.03 
6     3        0.668      0.735      1.11     5  

关于r - 如何用单个值替换数据框中每行的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73899338/

相关文章:

bash - 在文件中使用 sed 将 windows 路径替换为 linux 路径

python - 根据包含的字典键替换 Pandas DataFrame 列值

r - 来自 xtable 的 table* 环境

r - 使用 setNames 替换 R 数据框列中的多个值时出现奇怪的行为

r - 使用 DBSCAN 对 GPS 数据进行聚类,但聚类没有意义(就大小而言)

r - 如何根据R中的列相交数据框

python - 带有列子集的数据框 drop_duplicates

r - R 中的聚类分析 : determine the optimal number of clusters

python - 如何获取包含与索引对应的特定值的列列表作为 Pandas 数据框中的新列?

python - 用字符串值替换数据框中的 NaN