For example : I have frame with 4 columns and I want divide columns A and B by C, but I want unchanged column ID
A B C ID
4 8 23 1
5 12 325 2
6 23 56 3
73 234 21 4
23 23 213 5
The result which i expect is
A B C ID
0,173913043 0,347826087 1 1
0,015384615 0,036923077 1 2
0,107142857 0,410714286 1 3
3,476190476 11,14285714 1 4
0,107981221 0,107981221 1 5
or without the column C, doesn't matter
So, I have the code which give me only columns A and B without the column 'ID'
columns_to_divide <- c(1,2)
results <- results[,columns_to_divide ]/results[,3]
CodePudding user response:
We can use mutate
, which creates or alters the values in a column. across
says to alter columns A and B, and then we can define a function to divide both of these columns by C.
library(dplyr)
dat %>% mutate(across(c(A, B), function(x) x/C))
A B C ID
1: 0.17391304 0.34782609 23 1
2: 0.01538462 0.03692308 325 2
3: 0.10714286 0.41071429 56 3
4: 3.47619048 11.14285714 21 4
5: 0.10798122 0.10798122 213 5
CodePudding user response:
div = c("A", "B")
div_by = "C"
DF[div] <- DF[div] / DF[[div_by]]
# A B C
# 1 0.17391304 0.34782609 23
# 2 0.01538462 0.03692308 325
# 3 0.10714286 0.41071429 56
# 4 3.47619048 11.14285714 21
# 5 0.10798122 0.10798122 213
Data
DF data.frame(
A = c(4, 5, 6, 73, 23), B = c(8, 12, 23, 234, 23), C = c(23, 325, 56, 21, 213)
)
CodePudding user response:
Create Columns
A <- c(4, 5, 6, 73, 23)
B <- c(8, 12, 23, 234, 23)
C <- c(23, 325, 56, 21, 213)
ID <- c(1, 2, 3, 4, 5)
Add to data frame
df = data.frame(A, B, C, ID)
divide by and print
df$A <- df$A / df$C
df$B <- df$B / df$C
df$C <- df$C / df$C
print(df)