问题描述
我是R的新手,我一直在尝试乘法和替换数据框中的某些值,但均未成功.基本上,我想做的是,当我的df(任意列)中的值是0 <x <1,将其乘以10,然后用该方程式的结果替换该值.
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 column) is0 < x < 1, multiplicate it by 10 and then replace that value with the result of this equation.
瞥见我的df,以防万一...
A glimpse to my df just in case...
'data.frame': 404 obs. of 15 variables:
$ D3: num 16.1 17.1 16.1 16.1 17.2 ...
$ TH : num 9.9 8.6 9.7 7.7 7.6 7.6 8.7 9.8 9.8 7.7 ...
$ D2 : num 33.3 29.3 30.3 29.3 33.3 ...
$ D1 : num 15.1 14.1 21.1 16.1 19.1 ...
$ P : num 20.7 14.1 19.2 18.2 12.1 ...
$ D5 : num 9.9 11.1 11.9 11.1 11.1 ...
$ D13: num 13.1 14.1 13.1 13.8 12.9 ...
$ D7 : num 11.8 11.1 12.1 14.1 12.1 ...
$ D16: num 12.9 12.1 12.9 11.1 12.9 12
例如,如果我的数据框中的值为0.15,我希望它为15.
For example, if a value from my data frame is 0.15 I want it to be 15.
推荐答案
一种选择是根据表达式创建逻辑矩阵.从数据集中提取值,乘以10并更新结果
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
或者如果我们不想替换初始对象,请使用 replace
df2 <- replace(df1, i1, df1[i1] * 10)
一个 tidyverse
选项加上一些其他检查列类型的选项将是
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 ~ .))
这篇关于根据R中的条件乘和替换数据帧中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!