Reputation: 71
I have a dataset where I want to change values of few columns. This is a dummy dataset
A <- c(1, 2, 1, 0, 1, 2)
B <- c(0, 2, 2, 0, 1, 1)
C <- c(1, 2, 1, 0, 1, 0)
Here D is the dataset containing A, B, C column
D <- data.frame(A, B, C)
Here I want to replace values of A and C.
1 will be 1
2 will be 0
0 will be 2
New dataframe should be having simialr results for A and C
A = c(1, 0, 1, 2, 1, 0)
C = c(1, 0, 1, 2, 1, 2)
Hence, I wrote a function
A2_risk <- function(x){
2 - x
}
Function works perfectly when I call just vectors.
When I am trying to write a for loop or apply function, it is creating issues. lapply function converts it into list not in a dataframe. Real dataset has many columns to be converted. Hence, I need a function or loop to do everything in one shot.
Thank you
Upvotes: 0
Views: 50
Reputation: 683
As an alternative you can use purrr
:
library(purrr)
data.frame(map_if(D, names(D) %in% c('A', 'C'), ~ 2-.x))
# A B C
# 1 1 0 1
# 2 0 2 0
# 3 1 2 1
# 4 2 0 2
# 5 1 1 1
# 6 0 1 2
Upvotes: 1
Reputation: 10375
Edit:
A2_risk <- function(i){
if (kol[i]) {
D[,i]
} else {
2-D[,i]
}
}
kol=grepl("B",colnames(D))
sapply(1:ncol(D),A2_risk)
[,1] [,2] [,3]
[1,] 1 0 1
[2,] 0 2 0
[3,] 1 2 1
[4,] 2 0 2
[5,] 1 1 1
[6,] 0 1 2
If you wanted say B and C you would use kol=grepl("B|C",colnames(D))
.
Upvotes: 0
Reputation: 50668
Using dplyr
you can do
library(dplyr)
D %>% mutate(across(c(A, C), A2_risk))
# A B C
#1 1 0 1
#2 0 2 0
#3 1 2 1
#4 2 0 2
#5 1 1 1
#6 0 1 2
Or in base R
mapply(function(col, nm) if (nm %in% c("A", "C")) A2_risk(col) else col, D, names(D))
Upvotes: 2