Message-ID: <3916e2d9-a21e-635b-5b48-65494c4d0e15@sapo.pt>
Date: 2021-09-02T14:01:17Z
From: Rui Barradas
Subject: Loop over columns of dataframe and change values condtionally
In-Reply-To: <CAMk+s2T0TaPuYZDywiOH7YOZgr8WUjusN=mDpxP4mMyQ=nW=Uw@mail.gmail.com>
Hello,
In the particular case you have, to change to NA based on condition, use
`is.na<-`.
Here is some test data, 3 times the same df.
set.seed(2021)
df3 <- df2 <- df1 <- data.frame(
x = c(0, 0, 1, 2, 3),
y = c(1, 2, 3, 0, 0),
z = rbinom(5, 1, prob = c(0.25, 0.75)),
a = letters[1:5]
)
# change all columns
is.na(df1) <- df1 == 0
df1
# only one column
is.na(df2[, 2]) <- df2[, 2] == 0
df2
# change several columns given by an index
is.na(df3[c(1, 3)]) <- df3[c(1, 3)] == 0
df3
Hope this helps,
Rui Barradas
?s 14:35 de 02/09/21, Luigi Marongiu escreveu:
> Hello,
> it is possible to select the columns of a dataframe in sequence with:
> ```
> for(i in 1:ncol(df)) {
> df[ , i]
> }
> # or
> for(i in 1:ncol(df)) {
> df[ i]
> }
> ```
> And change all values with, for instance:
> ```
> for(i in 1:ncol(df)) {
> df[ , i] <- df[ , i] + 10
> }
> ```
> Is it possible to apply a condition? What would be the syntax?
> For instance, to change all 0s in a column to NA would `df[i][df[i ==
> 0] = NA` be right?
> Thank you
>
>