Hi,
I have a data frame with three columns and 40 rows. The 1st two columns contain a value range from -1 to 1, and the 3rd column contains the sum of the two columns. Therefore, I would like to change values closer to zero, such as o.3,0.2,0.1,-0.1,-0.2,-0.3 in the 3rd columns to zero, and keep the rest as it was.
library(dplyr)
set.seed(2)
D = data.frame(from = runif(40, -1,1), to = runif(40,-1,1)) %>% dplyr::mutate(weight = from + to)
Thanks for the solution. However, could you please be able to show me how to make values closer to zero to be closer to zero, not exactly zero?
In simple words, I want to decrease the distance between zero and the values closer to zero while keeping values far from zero the same.
I am sorry; my question was about the weight variable in the D data frame assuming weight could be the sum/average or product of the 1st two columns.
something like below
# Compute the third column using the two columns
D$weight <- (D$from + D$to) / 2
# Maintain a distance between zero and the values closer to zero to be low
D$weight <- ifelse(abs(D$weight) <= 0.2, D$weight/2, D$weight)
# Print the data frame
print(D)
You can use the ifelse function to change the values in the 3rd column based on a certain condition. The condition can be checking if the value is between -0.3 and 0.3 (inclusive) and then replacing those values with 0, otherwise keep the original value.
Alternatively you can also use the replace() function like this
D$weight[D$weight >= -0.3 & D$weight <= 0.3] <- 0
Both of the above code will update the 3rd column of dataframe, replacing the values between -0.3 and 0.3 with 0, leaving the rest of the values as they were.