weixin_41329348 2021-10-07 14:58 采纳率: 50%
浏览 54
已结题

Grouped by a specific variable, I want find the minimum value in the other columns and replace it


#This is the example data
dataa <- data.frame(x1 = 1:5,    # Create example data
                   x2 = 6:10,
                   x3 = 11:15,
                   x4 = c(1,1,2,2,2))

#Grouped by X4, I want to replace the minimum value in X1:X2 with the minimum value/2, which #means the 1 in X1 and 3 in X1 should be replaced with 0.5 and 1.5; 6 in X2 and 8 in X2 should be #replaced with 3 and 4, respectively.

#Because I will be calculate this in a big data with numerous colomuns, thus maybe I need a FOR #LOOP? However, my codes did not work:

for (j in 1:2) 
  {
  for(i in 1:2) 
    {
    if(dataa[,i]==min(dataa[,i]) & dataa$x4==j) #Wrong
      {
      dataa[,min(dataa[,i])]<-min(dataa[,i])/(sqrt(2))
      }
     }
   }

#Can you help me? 


  • 写回答

2条回答 默认 最新

  • slandarer MATLAB领域优质创作者 2021-10-07 23:14
    关注

    If it helps, please click accept,Thanks!
    try this:

    #This is the example data
    dataa <- data.frame(x1 = 1:5,    # Create example data
                       x2 = 6:10,
                       x3 = 11:15,
                       x4 = c(1,1,2,2,2))
     
    #Grouped by X4, I want to replace the minimum value in X1:X2 with the minimum value/2, which #means the 1 in X1 and 3 in X1 should be replaced with 0.5 and 1.5; 6 in X2 and 8 in X2 should be #replaced with 3 and 4, respectively.
     
    #Because I will be calculate this in a big data with numerous colomuns, thus maybe I need a FOR #LOOP? However, my codes did not work:
    
    
    for(j in 1:2) {
      for(i in 1:2){
        tmin=min(dataa[,i][dataa$x4==j])
        dataa[,i][dataa[,i]==tmin&dataa$x4==j]<-tmin/2
      }
    }
    dataa
    

    x1 x2 x3 x4
    0.5 3 11 1
    2.0 7 12 1
    1.5 4 13 2
    4.0 9 14 2
    5.0 10 15 2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月16日
  • 已采纳回答 10月8日
  • 创建了问题 10月7日

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊