Replace Multiple Values in Several Columns of Data Frame in R (2 Examples) | sapply() & replace()

preview_player
Показать описание
R code of this video:

x2 = 1:6,
x3 = 3:1)
data # Print example data

val_repl <- c(1, 3) # Specify values to be replaced
val_repl # Print vector of values

data_new1 <- sapply(data, # Replace values in all columns
function(x) replace(x, x %in% val_repl, 99))
data_new1 # Print updated data frame

col_repl <- c("x2", "x3") # Specify columns
col_repl # Print vector of columns

data_new2 <- data # Duplicate data frame
data_new2[col_repl] <- sapply(data_new2[col_repl], # Replace values in certain columns
function(x) replace(x, x %in% val_repl, 99))
data_new2 # Print updated data frame

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

Hello, Joachim, I have a slightly different problem than you discuss in this material. It is as follows: 1. Have a data frame, numeric values, and NA missing values in it. 2. Now I have to replace NA values with a set of values that I acquired after preparing the data frame. So there are different values for different NA indexes in df. Do you have any notion of how to cope with this problem? I'm trying different methods with no effect so far. Thank you in advance for your advice.

bernardokonski
Автор

It helps me, but I need to create a new raster using this replacement process after comparing values from two rasters. Do you know of a similar procedure?

anafreitas
Автор

Hi Joachim,
I have a challenge for you and your subscribers. Given a dataframe with multiple values per column cell how do we separate them out into new rows? For example we have dataframe with column x and column y. We will assume one row only. Lets see that the row has 1, 2, 3 in the x column cell and a, b, c in the y column cell. We need to separate them such that we have three rows. Row 1: 1 in x, a in y, Row 2, 2 in x, b in y, Row 3: 3 in x and c in y. This sounds simple but I cannot figure our how to clean this up to get that result. Any ideas or suggestions are welcome.

haraldurkarlsson
Автор

Why not use a dataset as an example as this is what others are using?

johnm