Reputation: 409
I need to replace specific values in a subset of columns in my dataframe. Specifically, I need to replace the value 1 in this subset of columns with 0.9999. I created a vector containing the column names of columns where replacement is needed. These columns must be subset by name and not column number.
peaches <- c( 0, 1, 0, 1)
bananas <- c( 0, 1, 1, 1)
apples <- c( 1, 1, 1, 1)
oranges <- c (0, 0, 0, 1)
fruits <- data.frame(peaches, bananas, apples, oranges)
vector <- c("apples", "bananas", "peaches")
My first attempt looked like this:
fruits[vector][fruits[vector] == 1] <- 0.9999
While it works for this small dataset, it is not transforming values in the large dataset I'm working with. Anyone know why?
Upvotes: 1
Views: 127
Reputation: 1771
You can try :
fruits[,vector] <- setDT(lapply(fruits[,vector], function(x) replace(x, x==1, 0.9999)))
peaches bananas apples oranges
1 0.0000 0.0000 0.9999 0.0000
2 0.9999 0.9999 0.9999 0.0000
3 0.0000 0.9999 0.9999 0.0000
4 0.9999 0.9999 0.9999 0.9999
Upvotes: 1
Reputation: 4150
Tidyverse solution
library(tidyverse)
peaches <- c( 0, 1, 0, 1)
bananas <- c( 0, 1, 1, 1)
apples <- c( 1, 1, 1, 1)
oranges <- c (0, 0, 0, 1)
fruits <- data.frame(peaches, bananas, apples, oranges)
vector <- c("apples", "bananas", "peaches")
fruits %>%
mutate_at(vector, ~ replace(., . == 1, .9999))
#> peaches bananas apples oranges
#> 1 0.0000 0.0000 0.9999 0
#> 2 0.9999 0.9999 0.9999 0
#> 3 0.0000 0.9999 0.9999 0
#> 4 0.9999 0.9999 0.9999 1
Created on 2020-01-14 by the reprex package (v0.3.0)
Upvotes: 2
Reputation: 377
Try this :
fruits[,vector][fruits[,vector] == 1] <- 0.9999
fruits[vector]
uses the fact that a data.frame is a list of vector (of the same length), maybe the "matrix" approach is more adapted.
Upvotes: 1