Reputation: 745
I have this data frame
Data structure(list(ID = 1:3, WEEK1 = c(1L, "A", 1.23), WEEK2 = c(1L, "AL", 1.68), WEEK3 = c("L", 1L, 2L)), class = "data.frame", row.names = c(NA, -3L))
DF ID WEEK1 WEEK2 WEEK3
1 1 A 1.23
2 1 AL 1.68
3 L 1 2
There is lot of random strings in the data frame. I would like to have negative conditional loop that change all values that not 1 to 0.
Like in data frame
DF ID WEEK1 WEEK2 WEEK3
1 1 O O
2 1 O O
3 O 1 O
This can change only known strings, but is it possible to change it to negative condition?
df %>% mutate(across(matches("WEEK"), chartr, old = '123', new = 'ABC'))
Upvotes: 0
Views: 94
Reputation: 39585
I would suggest next approach. You have to notice that all values in your dataframe are character strings:
#Data
Data <- structure(list(ID = 1:3, WEEK1 = c("1", "A", "1.23"), WEEK2 = c("1",
"AL", "1.68"), WEEK3 = c("L", "1", "2")), class = "data.frame", row.names = c(NA,
-3L))
The code:
#Loop
for(i in 2:dim(Data)[2])
{
Data[,i]<-ifelse(Data[,i]!='1',0,Data[,i])
}
Output:
ID WEEK1 WEEK2 WEEK3
1 1 1 1 0
2 2 0 0 1
3 3 0 0 0
Upvotes: 1