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]
Of Luigi Marongiu
> Sent: Thursday, September 2, 2021 3:35 PM
> To: r-help
> Subject: [R] Loop over columns of dataframe and change values condtionally
>
> Hello,
> it is possible to select the columns of a dataframe in sequence with:
> ```
> for(i in 1:ncol(df)) {
> df[
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?
3 matches
Mail list logo