Multiply and replace values in data frame according to condition in R

后端 未结 1 1807
执笔经年
执笔经年 2021-01-26 21:22

I\'m new to R and I\'ve been trying to multiply and replace certain values in my data frame with no success. Basically, what I want to do is that when a value from my df (any co

相关标签:
1条回答
  • 2021-01-26 21:46

    An option would be to create a logical matrix based on the expression. Extract the values from the dataset, multiply by 10 and update the results

    i1 <- df1 >0 & df1 < 1
    df1[i1] <- df1[i1] * 10
    

    Or with replace if we don't want to replace the initial object

    df2 <- replace(df1, i1, df1[i1] * 10)
    

    A tidyverse option with some additional checks for type of the column would be

     library(dplyr)
     df1 %>%
        mutate_if(is.numeric, ~ case_when(between(., 0, 1) ~ . * 10, TRUE ~ .))
    
    0 讨论(0)
提交回复
热议问题