Hi,
I have a 60 column dataset, 2 of them are units of measurement, and the measured numbers respectively.
in order to convert the numbers into just 1 unit, I have to write some formula that when the units are in percentages in 1 column, the corresponding value in the column number will change, I do it as below:
ifelse(df$unit=="%",df$number<-df$number-2)
a=ifelse(df$unit=="%",df$number-2,non)
b=a-2
c=paste(a,b,sep="")
but the following error was the result:
the condition has length > 1 and only the first element will be used
Hi @shohreh,
I'm not sure I completely understand your question but here is a simple dplyr way to modify the contents of multiple data frame columns, depending on the content of the units column.
suppressPackageStartupMessages(library(tidyverse))
(df <- data.frame(units = c("%","%","raw","raw","%"),
aa = c(20,15,0.6,0.5,40),
bb = c(10,12,0.4,0.7,28)))
#> units aa bb
#> 1 % 20.0 10.0
#> 2 % 15.0 12.0
#> 3 raw 0.6 0.4
#> 4 raw 0.5 0.7
#> 5 % 40.0 28.0
df %>%
mutate_at(vars(-units), ~ifelse(units=="%", ./100, .))
#> units aa bb
#> 1 % 0.20 0.10
#> 2 % 0.15 0.12
#> 3 raw 0.60 0.40
#> 4 raw 0.50 0.70
#> 5 % 0.40 0.28
hi @DavoWW
Thank you, let me be more clear,
my point is that if the units of the observation in some rows of one column were "%", then I want to do some calculations on the corresponding values of another column of that observations, for example:
units value
% 4
% 5
raw 10
I want to convert the values in the column value to be multiplied by 10, when their units are %, but not the raw.
could you help me with that?
iris$Sepal.Length[iris$Species == "setosa"] <- iris$Sepal.Length[iris$Species == "setosa"] * 10
# with your df
# df$number_old # this allow to backup the column before you mutate it, if note needed you can skip it
# df$number[df$unit == "%"] <- df$number[df$unit == "%"] * 10
EDIT: you want all columns except units ones to be transformed
So lets say that your units columns are named unit1 and unit2
Still, I don't know which one of the two units columns will dictate the transformation.
I choosed unit1